开发者

Authorise part of a View IN ASP.NET MVC

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, encryptedTi开发者_开发百科cket) { 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.


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 
<% } %>


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>
<% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜