2015-07-13 92 views
0

我在我的MVC應用程序中使用基於OWIN的身份驗證。 我所有的控制器和操作方法都使用自定義的AuthorizeAttribute進行保護。ASP.Net MVC 5 - OWIN身份驗證登錄重定向顯示消息

當前,如果用戶請求權限不足的頁面(由於用戶不在可以訪問該功能的組中,用戶無法訪問),他將被重定向到登錄頁面。 此行爲可能會讓用戶感到困惑,因爲他不知道他爲什麼被重定向到登錄頁面。

在這種情況下是否可以顯示消息? ...可以OWIN添加一個參數到登錄頁面請求(類似於ReturnUrl參數)?

感謝您的幫助。

編輯:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 
public class FunctionAuthorizeAttribute : AuthorizeAttribute 
{ 
    public IUserInformationService UserInformationService { get; set; } 
    public IGenericParameterService GenericParameterService { get; set; } 
    public String FunctionName { get; set; } 

    public FunctionAuthorizeAttribute(String functionName) 
    { 
     FunctionName = functionName; 
    } 

    protected override Boolean AuthorizeCore(HttpContextBase httpContext) 
    { 
     var parameter = GenericParameterService.GetCommonParameters(); 
     if (!parameter.CacheSecurityParameter) 
      parameter = GenericParameterService.GetCommonParameters(false); 

     return !parameter.EnableAuthentication || UserInformationService.HasAccess(FunctionName) 
    } 
} 
+0

你能顯示你的自定義屬性嗎? – Kamo

+0

@Kamo當然,但你不會在那裏發現任何有趣的事情......我想。 我已將代碼添加到問題中。 – musium

回答

1

使用可以使用會話存儲。我通常將消息存儲在會話變量的下一個屏幕顯示中(作爲列表)。佈局頁面將負責顯示相應的消息:在查看/帳號/ Login.cshtml與代碼

SessionMessage.AddMessage("Huh - you should login first", SessionMessage.MessageType.warning); 

@foreach (SessionEntry item in SessionMessage.GetSessionEntries()) 
{ 
    <div class="alert [email protected](Enum.GetName(typeof(SessionMessage.MessageType), item.MessageType).ToLower())"> 
     <button type="button" class="close" data-dismiss="alert"></button> 
     @item.Message 
     </div> 
} 

與所有的休息here

+0

很酷,非常感謝你 – musium

+0

你可能會更好地將錯誤存儲在TempData對象中,因爲它只能用於一個請求,然後自動清除。 – Derek

+0

我遇到了TempData問題,信息在多個重定向中丟失(特別是在OWIN和Azure Active Directory的上下文中)。因此我已轉到會話方法。 –