我在。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>
我找到了这样的答案,所以只有当您登录时才能看到列表
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
@if (Request.IsAuthenticated)
{
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Roles", "Index", "Roles")</li>
<li>@Html.ActionLink("Evaluaties", "About", "Home")</li>
}
else
{
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Roles", "Index", "Roles")</li>
}
</ul>
@Html.Partial("_LoginPartial")
</div>
为操作方法使用授权属性:
//you may use it without role name: [Authorize]
[Authorize(Roles = "Begeleider")]
public ActionResult About()
{
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();
}
如果你想隐藏非角色用户的链接,使用:
if(User.IsInRole("Evaluaties")){
<li>@Html.ActionLink("Evaluaties", "About", "Home")</li>
}