1

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?

1 Answer 1

1

So you have a couple options on where to write that code:

  1. 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.

  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.