ASP. NET Web API Add exception filter

Source: Internet
Author: User

I. Defining an exception filter

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Http.Filters;
Using System.Net;
Using System.Net.Http;

Namespace WebApi
{
public class Notimplexceptionfilter:exceptionfilterattribute
{
public override void Onexception (httpactionexecutedcontext context)
{
if (context. Exception is NotImplementedException)
{
Context. Response = new Httpresponsemessage (httpstatuscode.notfound);
}
}
}
}

Note: Httpstatuscode.notfound status code is just random, I'm here

Two. Reference filter

(1) Global use (valid for all actions), register exception filter in Global.asax, as follows

public class WebApiApplication:System.Web.HttpApplication
{

protected void Application_Start ()
{
Globalconfiguration.configure (Webapiconfig.register);

    GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (New Notimplexceptionfilter ());
}
}

(2) Specify action to use

[Notimplexceptionfilter]

Public ienumerable<contact> Get (string id = null)
{

...

    throw new NotImplementedException ("This method was not implemented");

}

Three. Action plus reference for the controller
Public ienumerable<contact> Get (string id = null)
{
var thecontact= from contact in Contacts
where contact. ID = = ID | | String. IsNullOrEmpty (ID)
Select contact;
if (thecontact = = NULL | | thecontact. Count () ==0)
{
var resp = new Httpresponsemessage (httpstatuscode.notfound)
{
Content = new Stringcontent (string. Format ("No Product with Id={0}", ID),
Reasonphrase = "Product ID not Found"
};
throw new NotImplementedException ("This method was not implemented");
}
return thecontact;
}

ASP. NET Web API Add exception filter

Related Article

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.