[英]MVC 3 AuthorizeAttribute Redirect with Custom Message
如何创建自定义AuthorizeAttribute,以字符串参数的形式指定消息,然后将其传递到登录页面?
例如,理想情况下执行此操作会很酷:
[Authorize(Message = "Access to the blah blah function requires login. Please login or create an account")]
public ActionResult SomeAction()
{
return View();
}
然后,在Login操作中,我可以这样做:
public ActionResult Login(string message = "")
{
ViewData.Message = message;
return View();
}
最后在视图中我可以这样做:
@if (!String.IsNullOrEmpty(ViewData.Message))
{
<div class="message">@ViewData.Message</div>
}
<form> blah blah </form>
基本上我想将自定义消息传递到登录页面,以便我可以显示特定于用户在该特定时间尝试访问的消息。
你可以尝试这样的事情:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public string Message { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
var result = new ViewResult();
result.ViewName = "Login.cshtml"; //this can be a property you don't have to hard code it
result.MasterName = "_Layout.cshtml"; //this can also be a property
result.ViewBag.Message = this.Message;
filterContext.Result = result;
}
用法:
[CustomAuthorize(Message = "You are not authorized.")]
public ActionResult Index()
{
return View();
}
web.config中
<authentication mode="Forms">
<forms name="SqlAuthCookie"
loginUrl="~/Account/LogOnYouHavenotRight"
timeout="2880" />
</authentication>
控制器:
public ActionResult LogOn()
{
return View();
}
public ActionResult LogOnYouHavenotRight()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
}
在两个视图中:
Html.BeginForm("LogOn", "Account" )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.