2017-09-15 140 views
2

問題:只要普通用戶嘗試訪問只能由管理員訪問的頁面,用戶總是被重定向到登錄而不是訪問被拒絕的頁面。Asp Net核心授權

問題:每當用戶訪問受限制的頁面時,普通用戶如何看到拒絕訪問頁面?

控制器:

[Authorize(Roles = "Administrator")] 
public class AdminOnlyController: Controller{ 

} 

Startup.cs

app.UseIdentity(); 

app.UseCookieAuthentication(new CookieAuthenticationOptions() 
{ 
      AuthenticationScheme = "FirstCookieAuthentication", 
      AutomaticAuthenticate = true, 
      AutomaticChallenge = true, 
      AccessDeniedPath = new PathString("/Forbidden/"), 
      LoginPath = new PathString("/Conotroller/Login"), 
}); 
+0

請參閱更新 –

回答

0

拒絕訪問僅僅是一個狀態代碼一樣沒有找到,內部錯誤等要管理狀態代碼,你可以使用中間件「app.UseStatusCodePages」。

代碼:

if (env.IsDevelopment()) 
{ 
//  see something more here 
} 
else 
{ 
     app.UseStatusCodePagesWithReExecute("/StatusCode/{0}"); 
} 

然後裏面StatusCodeController,打造您提供的路線,前相匹配的操作結果:

[HttpGet("/StatusCode/{statusCode}")] 
    public IActionResult Index(int statusCode) 
    { 
     string statusmessage = ""; 
     switch (statusCode) 
     { 
      case 400: 
       statusmessage = "Bad request: The request cannot be fulfilled due to bad syntax"; 
       break; 
      case 403: 
       statusmessage = "Forbidden"; 
       break; 
//all codes here... 
      default: 
       statusmessage = "That’s odd... Something we didn't expect happened"; 
       break; 
     } 

     // return appropriate view 
     // or same view with different message, eg from ViewBag 
    } 
+0

uhmm我檢查了響應狀態碼,它總是返回200即使我作爲普通用戶訪問受限制的頁面。 –

0

我所做的是創建一個實現IActionFilter接口和一個自定義屬性繼承Attribute類。所以基本上我把我的代碼放在On Action Executing Method中。不過,我也讀過this關於不創建自定義屬性的線程。但是我沒有閱讀評論部分的全部討論。無論如何,這適用於我的情況。