2017-08-25 65 views
0

我有一個自定義授權屬性。如何從自定義授權屬性返回401代碼?

當這在WebAPI中實現時,OnActionExecuting方法通過了一個HttpActionContext對象,我可以在其中更新響應,例如,

actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 

但是,在MVC實現時傳遞的對象是ActionExecutingContext對象,其中包含的迴應,但它是隻讀的,這意味着我不能以同樣的方式返回授權拒絕。

,因爲它是隻讀這是行不通的:

context.HttpContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 

這也將無法正常工作,因爲它是隻讀:

HttpContext.Current.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 

我怎樣才能在MVC可寫的反應,我可以這樣設置?

+0

這是一個很好的資源:https://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging –

+0

聽起來你正在做定製ActionFilter代替AuthorizationFilter。 –

回答

1

嘗試設置的結果,而不是響應;

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    // Authorization code here - if not authorized: 

    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized); 
} 
+0

這對我有用 - 謝謝 – CompanyDroneFromSector7G