MVC 3 使用自定义消息授权属性重定向
本文关键字:授权 属性 重定向 自定义消息 MVC | 更新日期: 2023-09-27 17:55:35
如何创建自定义 AuthorizeAttribute,以字符串参数的形式指定消息,然后将其传递到登录页面?
例如,理想情况下,这样做会很酷:
[Authorize(Message = "Access to the blah blah function requires login. Please login or create an account")]
public ActionResult SomeAction()
{
return View();
}
然后,在登录操作中,我可以执行以下操作:
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" )