Authorise part of a View IN ASP.NET MVC

不打扰是莪最后的温柔 提交于 2019-12-13 05:03:18

问题


I am currently using the [Authorise] attribute in Controllers to restrict Views to be only visible if the website user is logged in.

But how do you restrict only part of a view? eg. Something like this...?

<% if(SomeoneIsLoggedIn) { %>
  <div id="protectedContent">...</div>
<% } %>

This method is called when a login is successful:

public static void CreateLoginCookie(User u)
{
  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(u.Id.ToString(), true, 9*60);
  string encryptedTicket = FormsAuthentication.Encrypt(ticket);
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.Now.AddHours(9) };
  HttpContext.Current.Response.Cookies.Add(cookie);
}

(that 9 hours doesn't seem to work btw, the code might be flawed but it's working - it lets people login)

Thanks in advance.


回答1:


You can check if the user is logged in by using this:

System.Web.HttpContext.Current.User.Identity.IsAuthenticated;

Then if the user is logged in you can add that to the ViewData:

ViewData["UserStatus"] = System.Web.HttpContext.Current.User.Identity.IsAuthenticated;

And then on your view you can do this:

<% if((bool)ViewData["UserStatus"]) { %>
  Content only for logged in users 
<% } %>



回答2:


Add a bool to your ViewModel:

public bool ShowProtectedSection {get; set;}

then populate that in your controller according to your business rules (If you use ASP.net Membership you can use Roles, or if you use your own logic then just use that to find out if the user has access).

Add the check to the View:

<% if(Model.ShowProtectedSection) { %>
  <div id="protectedContent">...</div>
<% } %>


来源:https://stackoverflow.com/questions/4881602/authorise-part-of-a-view-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!