在 ASP.NET MVC 中授权视图的一部分
我目前正在控制器中使用 [Authorise] 属性来限制视图仅在网站用户登录时可见。
但是如何仅限制视图的一部分呢?例如。像这样的东西...?
<% if(SomeoneIsLoggedIn) { %>
<div id="protectedContent">...</div>
<% } %>
当登录成功时会调用此方法:(
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);
}
顺便说一句,9 小时似乎不起作用,代码可能有缺陷,但它正在工作 - 它允许人们登录)
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用以下命令检查用户是否已登录:
然后,如果用户已登录,您可以将其添加到 ViewData:
然后在您的视图上您可以执行以下操作:
You can check if the user is logged in by using this:
Then if the user is logged in you can add that to the ViewData:
And then on your view you can do this:
将 bool 添加到您的 ViewModel:
然后根据您的业务规则将其填充到您的控制器中(如果您使用 ASP.net 成员资格,则可以使用角色,或者如果您使用自己的逻辑,则只需使用它来查明用户是否具有访问权限)。
将检查添加到视图中:
Add a bool to your ViewModel:
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: