是否授权一个视图在ASP.NET MVC的一部分 [英] Authorise part of a View IN ASP.NET MVC

查看:118
本文介绍了是否授权一个视图在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, encryptedTicket) { Expires = DateTime.Now.AddHours(9) };
  HttpContext.Current.Response.Cookies.Add(cookie);
}

(即9小时似乎并不BTW工作,code可能是有缺陷的,但它的工作 - 它让人们登录)

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

先谢谢了。

推荐答案

您可以检查,如果用户通过使用此登录:

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

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

然后,如果用户登录可以添加到ViewData的:

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

这篇关于是否授权一个视图在ASP.NET MVC的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆