MVC 3 AuthorizeAttribute重定向使用定制信息 [英] MVC 3 AuthorizeAttribute Redirect with Custom Message

查看:168
本文介绍了MVC 3 AuthorizeAttribute重定向使用定制信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能创建一个自定义AuthorizeAttribute在一个字符串参数的形式指定一个信息,然后通过沿到登录页面?

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

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

用法:

    [CustomAuthorize(Message = "You are not authorized.")]
    public ActionResult Index()
    {
        return View();
    }

这篇关于MVC 3 AuthorizeAttribute重定向使用定制信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆