2011-05-07 35 views
15

如何創建一個自定義的AuthorizeAttribute,它以字符串參數的形式指定消息,然後將其傳遞給登錄頁面?MVC 3 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> 

基本上我想傳遞一個自定義消息到登錄頁面,所以我可以顯示一條特定於用戶在該特定時間嘗試訪問的消息。

回答

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(); 
    } 
+3

如果我想重定向到一個特定的視圖/控制器/路由參數,怎麼會是誰? – ClayKaboom 2012-03-15 12:48:05

+1

@ClayKaboom看到這篇文章http://stackoverflow.com/questions/2472578/is-it-possible-to-use-redirecttoaction-inside-a-custom-authorizeattribute-clas – user1477388 2013-04-27 20:29:05

+0

請注意,你可能不想包括ViewName屬性中的「.cshtml」。當我做了,它尋找Login.cshtml.cshtml。 – AaronSieb 2016-07-13 16:04:05

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

只是整個答案的一部分,但如果你閱讀其他人,你可能會聰明到總結他們+1,無論如何.... – ppumkin 2013-01-03 14:17:22