我在.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中它只会是文本 –