Exception handling in the ASP. NET Web Api

Source: Internet
Author: User

This article main reference: Http://www.asp.net/web-api/overview/error-handling/exception-handling

1. If a Web API controller throws an uncaught exception, by default, most exceptions are converted to an HTTP response status code of 500 internal server error.

The httpresponseexception type is a special case. This exception returns any HTTP status codes that are specified in the exception constructor. For example, the following method if the parameter ID is invalid, the request returns 404.

 Public Product getproduct (int  ID) {    = repository. Get (ID);     if NULL     {         thrownew  httpresponseexception (httpstatuscode.notfound);    }     return  item;}

Of course you can also build a complete response message through httpresponseexception.

 PublicProduct GetProduct (intID) {Product Item=Repository.    Get (ID); if(Item = =NULL)    {        varRESP =NewHttpresponsemessage (httpstatuscode.notfound) {Content=NewStringcontent (string. Format ("No product with ID = {0}", id)), reasonphrase="Product ID not Found"        }        Throw Newhttpresponseexception (RESP); }    returnitem;}

Exception filter

You can crawl all unhandled exceptions by customizing an exception filter. Of course, excluding exceptions of type httpresponseexception , it is a special case because it returns an HTTP message directly.

The exception processor inherits from the System.Web.Http.Filters.IExceptionFilter interface. The quickest way to create a new exception handler is to inherit the System.Web.Http.Filters.ExceptionFilterAttribute class and override the (override) Onexception method.

Exception handlers in the Web API are very similar to exception handlers in MVC, although they come from different namespaces and functions.

The following example implements an exception filter that converts an notimplementedexception exception to an HTTP 501 error.

namespaceproductstore.filters{usingSystem; usingSystem.Net; usingSystem.Net.Http; usingSystem.Web.Http.Filters;  Public classNotimplexceptionfilterattribute:exceptionfilterattribute { Public Override voidonexception (Httpactionexecutedcontext context) {if(Context. Exception isnotimplementedexception) {context. Response=Newhttpresponsemessage (httpstatuscode.notimplemented); }        }    }}

How do I register these custom exception handlers?

The system provides the following three ways to register

1, action on the registration

 Public class productscontroller:apicontroller{    [notimplexceptionfilter]    Public contact getcontact ( int ID)    {        thrownew notimplementedexception ("This method was notimplemented ");    }}

2, register on the controller

[Notimplexceptionfilter]  Public class productscontroller:apicontroller{    Public Contact GetContact (int  ID)    {         thrownew notimplementedexception ("This method was notimplemented " );    }}

3. Global Registration

 Public Static class webapiconfig{    publicstaticvoid  Register (httpconfiguration config)    {        config. Filters.add (new  Productstore.notimplexceptionfilterattribute ());         // Other configuration code ...     }}

Httperror

The Httperror object provides a consistent method for returning an error message in an HTTP response message, and here is an example of returning a 404 error in an HTTP response message:

 PublicHttpresponsemessage GetProduct (intID) {Product Item=Repository.    Get (ID); if(Item = =NULL)    {        varMessage =string. Format ("Product with id = {0} not found", id); returnrequest.createerrorresponse (httpstatuscode.notfound, message); }    Else    {        returnrequest.createresponse (Httpstatuscode.ok, item); }}

The following example shows how to return the model validation error message via Httperror

 Public httpresponsemessage postproduct (Product item) {    if (!  Modelstate.isvalid)    {        return  request.createerrorresponse ( Httpstatuscode.badrequest, modelstate);    }     // implementation not shown...}
Httpresponseexception and Httperror used together
 PublicProduct GetProduct (intID) {Product Item=Repository.    Get (ID); if(Item = =NULL)    {        varMessage =string. Format ("Product with id = {0} not found", id); Throw Newhttpresponseexception (Request.createerrorresponse (httpstatuscode.notfound, message)); }    Else    {        returnitem; }}

Exception handling in the ASP. NET Web Api

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.