Sunil Chaudhry
Sunil Chaudhry

Reputation: 263

Same Web API return multiple formats

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.

Upvotes: 0

Views: 1235

Answers (1)

ebattulga
ebattulga

Reputation: 10981

Asp.net ApiController automatically do this

For example:

enter image description here

After that add Accept header just like this

enter image description here

Upvotes: 1

Related Questions