如何创建将重定向到登录如果返回false,类似于授权属性自定义属性 - ASP.NET MVC [英] How to create a custom attribute that will redirect to Login if it returns false, similar to the Authorize attribute - ASP.NET MVC
问题描述
我想谷歌搜索有关自定义属性的几件事情,但我仍然不知道如何去了解它....
I tried Googling a few things about custom attributes but I'm still not sure how to go about it....
我存储用户的一些重要细节在会话cookie(如用户名),一旦用户登录在..和所有我想要做的就是创建一个属性,其中如果
I'm storing a few important details of the user in Session cookies (ex UserID) once the user log's in.. and all I want to do is create an attribute where if the
如果(会话[用户名] == NULL)
然后它会重定向到登录就像[授权]属性呢。这样我可以应用在控制器级别无处不这个属性。
then it will redirect to login just like the [Authorize] attribute does. That way I can apply this attribute on the Controller level everywhere.
我应该覆盖授权属性?创建一个新的?我如何得到它重定向到登录呢?
Should I overwrite the Authorize attribute? Create a new one? How do I get it to redirect to login as well?
我还使用ASP.NET MVC 4
I'm also using ASP.NET MVC 4
感谢您的帮助。
推荐答案
您可以创建自定义 AuthorizeAttribute
并重写 AuthorizeCore()
和 HandleUnauthorizedRequest()
的要求。添加您自己的逻辑,会做检查和重定向如果必要的。
You can create a custom AuthorizeAttribute
and override AuthorizeCore()
and HandleUnauthorizedRequest()
as required. Add your own logic which will do the check and redirect if necessary.
我只是表示采用MVC的 ActionFilterAttribute
一个简单的例子(这是不是做认证/授权的最佳场所)
I'm just showing a simple example using MVC's ActionFilterAttribute
(which is not the best place to do authentication/authorization)
public class VerifyUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var user = filterContext.HttpContext.Session["UserID"];
if (user == null)
filterContext.Result = new RedirectResult(string.Format("/User/Login?targetUrl={0}",filterContext.HttpContext.Request.Url.AbsolutePath));
}
}
不要忘记设置会话[用户名]
变量在 /用户/登录
操作方法经过正确的用户验证。
Do not forget to set the Session["UserID"]
variable in your /User/Login
action method after proper user validation.
这篇关于如何创建将重定向到登录如果返回false,类似于授权属性自定义属性 - ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!