2017-08-25 160 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