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