开发者

MVC 3 AuthorizeAttribute Redirect with Custom Message

How can I create a custom AuthorizeAttribute that specifies a message in the form of a string parameter and then passes that along to the login page?

For example, ideally it would be cool to do this:

[Authorize(Message = "Access to the blah blah function requires login. Please login or create an account")]
public ActionResult SomeAction()
{
    return View();
}

Then, in the Login action, I could do something like this:

public ActionResult Login(string message = "")
{
    ViewData.Message = message;

    return View();
}

And finally in the view I can do this:

@if (!String.IsNullOrEmpty(ViewData.Message))
{
    <div class="message">@ViewData.Message</div>开发者_JAVA技巧;
}

<form> blah blah </form>

Basically I want to pass a custom message to the login page so I can display a message specific to what the user is trying to access at that particular time.


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" )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜