我在.net中爲學校創建了一個MVC項目,並使用此代碼僅向具有指定角色的特定用戶顯示我的視圖的某些部分。針對特定角色顯示部分視圖並隱藏未登錄用戶的導航按鈕
public ActionResult About()
{
if (User.IsInRole("Begeleider"))
{
var client = new WebClient();
var jsonLeerlingen = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));
var leerlingen = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Leerling>>(jsonLeerlingen);
ViewBag.Message = leerlingen;
}
return View();
}
,當我登錄與具有作用「Begeleider」的用戶,但是當我點擊導航按鈕我在CSHTML得到一個錯誤這工作。這是合乎邏輯的,因爲我在這裏調用代碼,但是當我沒有以正確的角色登錄時無法訪問它。但是,我如何解決它呢?
@{
ViewBag.Title = "Evaluaties";
var leerlingen = List<ASPNetMVCExtendingIdentity2Roles.Domain.Leerling>)ViewBag.Message;
}
<h2>@ViewBag.Title.</h2>
<h4>Leerlingen</h4>
<table>
@foreach (var leerling in leerlingen)
{
<tr>
<td>@leerling.Naam</td>
<td>@leerling.Email</td>
</tr>
}
</table>
<h4>Evaluaties</h4>
@* Here shall be the same code as above but for a Leerling himself he'll only be able to see himself and his own Evaluation(Evaluatie), Haven't figuerd it out yet. *@
導航是這個,最後一個li是不應該爲未登錄用戶可見的。
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Roles", "Index", "Roles")</li>
<li>@Html.ActionLink("Evaluaties", "About", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
評估不是角色,但如果我使用角色Begeleider,則會出現以下錯誤: _App.Web_tdbnlmww.dll中發生類型爲「System.NullReferenceException」的異常,但未在用戶代碼中處理 附加信息:De objectverwijzing is niet op een exemplaar van een object ingesteld._ –
而你發送的第一部分我不認爲我可以使用它,因爲另一個角色有不同的看法,它還沒有完成,因爲它只需要1個Leerling和1個評估不同localhostlinks但是這是我現在有: '如果(User.IsInRole( 「Begeleider」)){ 相同 代碼如上 } 如果(User.IsInRole( 「Leerling」)) { 相同的代碼,但將在以後更改 } –
不能使用if(User.IsInRole(「Evaluaties」)){...'在我的.cshtml中它只會是文本 –