Contact Manager web API example [4] Exception Handling)

Source: Internet
Author: User
Tags http status code 500

The contact Manager web API is an Asp.net web API example program that demonstrates how to publish contact information through ASP. NET web API and allows you to add and delete contacts. The example address is http://code.msdn.microsoft.com/contact-manager-web-api-0e8e373d.

Contact Manager web API example [1] The CRUD operation has been introduced,

Contact Manager web API example [2] web API routing introduces web API routing.

The contact Manager web API example [3] Paging and querying mainly introduces the query and paging support of odata.

This article mainly introduces httpresponsemessage for webapi exception handling.

What happens if the Controller of the web API throws an exception? By default, exceptions are most often translated into an HTTP status code 500 (internal server error) response.

Httpresponseexception classThis is a special case. Ability to construct response information. This exception can be returned.AnyHTTP status code. For example, in the following example, if the ID parameter does not exist, the 404 (not found) status code will be returned.

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 Filtering)

You can writeException Filter)To handle web API exceptions. When a controller method throwsAny unprocessed exceptions, It is notHttpresponseexceptionThe exception filter is executed.HttpresponseexceptionTypeThis is a special case because it is specially designed to send HTTP responses back and forth.

Exception filtering implementationSystem. Web. http. Filters. iexceptionfilter Interface. In any case, you only need to inheritSystem. Web. http. Filters. exceptionfilterattributeClassOverride)OnexceptionMethod.

Namespace contactmanager. Filters
{
Public class logexceptionfilter: exceptionfilterattribute
{
Public override void onexception (httpactionexecutedcontext actionexecutedcontext)
{
// Add two lines of trace code

Trace. traceerror ("exception: {0}", actionexecutedcontext. Exception. Message );
Trace. traceerror ("request URI: {0}", actionexecutedcontext. Request. requesturi );

Base. onexception (actionexecutedcontext );
}
}
}

You can also control the HTTP response for the client to receive. InHttpactionexecutedcontextParametersModify or setResultAttribute. We add a notimplexceptionfilter class, which inherits the samePredictionfilterattributeClass and override OnexceptionMethod.

Namespace contactmanager. Filters
{
Public class notimplexceptionfilter: exceptionfilterattribute
{
Public override void onexception (httpactionexecutedcontext actionexecutedcontext)
{
// Add two lines of trace code

Trace. traceerror ("exception: {0}", actionexecutedcontext. Exception. Message );
Trace. traceerror ("request 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 ("method not executed ");

Base. onexception (actionexecutedcontext );
}
}
}

Registration exception Filtering

There are two ways to register for exception filtering.

First, you can register to the globalGlobalconfiguration. configuration. FiltersSet. When an unhandled exception occurs, the exception filtering set applies to all web API controller actions. (The exception type httpresponseexception will also be executed ). In the global. asax fileApplication_startRegister it.

Public static void registerapis (httpconfiguration config)
{
......

Config. Filters. Add (New logexceptionfilter ());

}

 

Protected void application_start ()
{
Registerapis (globalconfiguration. configuration );
}

Second, you can register an exception filter to the specified action method by specifying the attribute. For example:

[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 ("this method is not executed ");
}
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 filtering is similar to ASP. net mvc in ASP. NET Web APIs. In any case, they are distributed in different namespaces. Note,HandleerrorattributeClassASP. net mvc cannot handle exceptions of web API controller.

 

References· System. Web. HTTP

· System. net. HTTP

· Exception Handling in ASP. NET web API

· ASP. NET web API Exception Handling

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.