Reputation: 817
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "search/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//JSON RESPONSE SETTING
config.Formatters.Clear();
config.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
config.EnableSystemDiagnosticsTracing();
}
ReplyController.cs
public class ReplyController: ApiController
{
[HttpGet]
public HttpResponseMessage getReply()
{...}
}
and I write json return custom error code below:
401 Bad Request - {meta:{code:401, msg='invalid params'}}
I want to write json return code for 404 http status.
whhere I write? controller class? webconfig.cs? Global.asax?
Upvotes: 1
Views: 649
Reputation: 435
So you have a couple options on where to write that code:
You can add a global filter that handles the OnError condition, and then have that filter return back a proper JSON response. There are a few different examples of that if you google around.
What I like to do, is have a custom BaseApiController class that has an ExecuteRequest method that takes a lambda delegate as it's parameter, and then inside the ExecuteRequest method body I can do all my setup before I call the delegate and my teardown and error handling after I call the delegate. I went this way b/c I use SimpleInjector as my DI framework and it was a pain to get custom filters to get DI injected, AND run in the order I wanted them to.
Let me know if that makes sense, but I think that would work well for you here, b/c then you could just handle that in a try/catch and be good to go.
Upvotes: 1