Contact Manager Web API 示例[4] 異常處理(Exception Handling)


聯系人管理器web API是一個Asp.net web api示例程序,演示了通過ASP.NET Web API 公開聯系信息,並允許您添加和刪除聯系人,示例地址http://code.msdn.microsoft.com/Contact-Manager-Web-API-0e8e373d

Contact Manager Web API 示例[1]CRUD 操作 已經做了一個基本的介紹,

Contact Manager Web API 示例[2] Web API Routing 介紹Web API Routing。

Contact Manager Web API 示例[3] 分頁和查詢(Paging and Querying)主要介紹OData的查詢和分頁支持。

本文主要介紹WebAPI的異常處理HttpResponseMessage。

如果 Web API 的 controller 擲出一個異常(exception),會發生什么事?默認下,最常是會把例外轉譯為一個 HTTP 狀態代碼 500 (Internal Server Error) 回應。

HttpResponseException 類 是一個特別情況。能夠構建回應的信息, 這個例外能回傳任何 HTTP 狀態代碼。例如,下面例子,如果 id 參數不存在,會回傳 404 (Not Found) 狀態代碼。

public HttpResponseMessage<Contact> Get(int id)
        {
            var contact = this.repository.Get(id);
            if (contact == null)
            {
                var response = new HttpResponseMessage();
                response.StatusCode = HttpStatusCode.NotFound;
                response.Content = new StringContent("Contact not found");
                throw new HttpResponseException(response);
            }
            var contactResponse = new HttpResponseMessage<Contact>(contact);

            //set it to expire in 5 minutes
            contactResponse.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(30));
            return contactResponse;
        }

異常過濾 (EXCEPTION FILTERS)

你可以通過編寫 異常過濾(Exception Filter)來自己處理 Web API 的異常。當一個 controller 方法拋出任何未處理的例外,它並不是 HttpResponseException 異常,異常過濾被會執行。HttpResponseException 型別是一種特別情況,因為它是特別設計來回傳 HTTP 響應。

異常過濾實現 System.Web.Http.Filters.IExceptionFilter 接口。不管如何,只需要繼承 System.Web.Http.Filters.ExceptionFilterAttribute 然后重寫(override) OnException 方法。

namespace ContactManager.Filters
{
    public class LogExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //增加二行 Trace 代碼

            Trace.TraceError("異常: {0}", actionExecutedContext.Exception.Message);
            Trace.TraceError("請求 URI: {0}", actionExecutedContext.Request.RequestUri);

            base.OnException(actionExecutedContext);
        }
    }
}

你也能自行控制 HTTP 響應讓 Client 接收。在 HttpActionExecutedContext 參數 去修改或設置 Result 屬性。我們新增一個 NotImplExceptionFilter 類別,一樣繼承 ExceptionFilterAttribute 類和重寫 OnException 方法。

namespace ContactManager.Filters
{
    public class NotImplExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //增加二行 Trace 代碼

            Trace.TraceError("異常: {0}", actionExecutedContext.Exception.Message);
            Trace.TraceError("請求 URI: {0}", actionExecutedContext.Request.RequestUri);

            if(actionExecutedContext.Result==null)
            {
                actionExecutedContext.Result = new  HttpResponseMessage();

            }
            //HttpStatusCode.NotImplemented = 501 
            actionExecutedContext.Result.StatusCode = HttpStatusCode.NotImplemented ;
            actionExecutedContext.Result.Content = new StringContent("方法未執行");

            base.OnException(actionExecutedContext);
        }
    }
}

注冊異常過濾

有二種方法可以去注冊異常過濾。

第一,你可以注冊到全局的 GlobalConfiguration.Configuration.Filters 集合。當發生未處理的異常,異常過濾集合中會作用在所有 Web API controller action。(異常類型 HttpResponseException 也會被執行)。我們必須在 Global.asax 文件的 Application_Start 注冊它。

public static void RegisterApis(HttpConfiguration config)
{
   ……

    config.Filters.Add(new LogExceptionFilter());

}

 

protected void Application_Start()
{
         RegisterApis(GlobalConfiguration.Configuration);
}

第二,你可以注冊異常過濾至指定的 action 方法,通過指定屬性的方式。例如以下范例:

        [HttpGet]
        [NotImplExceptionFilter]
        public HttpResponseMessage<Contact> Get(int id)
        {
            var contact = this.repository.Get(id);
            if (contact == null)
            {
                //var response = new HttpResponseMessage();
                //response.StatusCode = HttpStatusCode.NotFound;
                //response.Content = new StringContent("Contact not found");
                //throw new HttpResponseException(response);
                throw new NotImplementedException("此方法未執行");
            }
            var contactResponse = new HttpResponseMessage<Contact>(contact);

            //set it to expire in 5 minutes
            contactResponse.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(30));
            return contactResponse;
        }

異常過濾在 ASP.NET Web API 與 ASP.NET MVC 類似。不管如何,他們分布在不同命名空間里。特別說明,HandleErrorAttribute 使用在  ASP.NET MVC,無法拿來處理 Web API controller 的異常。

 

參考資料· System.Web.Http

· System.Net.Http

· Exception Handling in ASP.NET Web API

·ASP.NET Web API Exception Handling


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM