簡體   English   中英

在ASP.NET MVC 4 ActionFilterAttribute中引發異常的正確方法

[英]Correct way to raise an exception in an ASP.NET MVC 4 ActionFilterAttribute

請注意,這是針對MVC 4中的ApiController,盡管我認為它不應該改變任何東西。

 public class OAuthFilter : System.Web.Http.ActionFilterAttribute
 {
       public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
       {
              if (checkVerified())
              {
                   // How to raise a 401 or some other type of exception.
              }
       }        
 }

您可以設置HttpActionContext的result屬性:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    if (checkVerified())
    {
        actionContext.Response = 
            new HttpResponseMessage(HttpStatusCode.Unauthorized);
    }
}

你可能只是扔:

throw new HttpResponseException(HttpStatusCode.Unauthorized);

但我沒有檢查那個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM