如何创建自定义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>
基本上我想将自定义消息传递到登录页面,这样我就可以显示特定于该特定时间用户尝试访问的消息。
答案 0 :(得分:23)
您可以尝试这样的事情:
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();
}
答案 1 :(得分:3)
的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" )