0

I am working on a Asp.Net Web API project, where I need to create it in a way so that 2 different clients can consume it and get response in there desired formats.

Need to provide support for both JSON and XML formats.

I have tried something in Register method in WebApiConfig file:

public static void Register(HttpConfiguration config)  
{  
    // Adding formatter for Json   
    config.Formatters.JsonFormatter.MediaTypeMappings.Add(  
        new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));  
      
    // Adding formatter for XML   
    config.Formatters.XmlFormatter.MediaTypeMappings.Add(  
        new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));  
}  

Here client can consume API but need to pass query string type=json or xml to get response in desired format.

http://localhost:1312/api/Blog?type=xml
http://localhost:1312/api/Blog?type=json 

Is there a better way to detect client's desired format and respond accordingly? If we get it from header of request or something like that, TIA.

1
  • Use Content-Type header to detect the incoming request format also you can use Accept header to decide what type of response to send Commented Jul 19, 2021 at 5:45

1 Answer 1

1

Asp.net ApiController automatically do this

For example:

enter image description here

After that add Accept header just like this

enter image description here

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

5 Comments

thanks for the response @ebattulga, we can add Accept in ajax call, can we add the same in angular httpclient or need to do handle that separately?
@SunilChaudhry of course can add Accept header in different clients (HttpClient, Angular, Javascript ...etc ). If you want, you can handle header from your action of controller.
thanks @ebattulga, as you said APIController itself take care of requested format, then its required only from client to add it in Accept header of request and no need to do anything from API side, right?
I am getting always JSON, tried with Access header as application/xml. DO you have any idea how to fix it? Also is there a way to always return JSON if no particular type is required(.)?
I can't tell you your problem without show some code. You can edit your post to add some code. After that, mention here

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.