MVC 3 AuthorizeAttribute Redirect with Custom Message

不想你离开。 提交于 2019-11-29 01:28:54

You can try something like this:

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

Usage:

    [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>

Controller:

public ActionResult LogOn()
    {
        return View();
    }

    public ActionResult LogOnYouHavenotRight()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
    }

In both Views:

Html.BeginForm("LogOn", "Account" )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!