How to force ASP.NET Web API to return JSON or XML data based on my input?

前端 未结 7 1885
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 12:56

I try to get the output XML or JSON data based on my input. I used the below WEB API code but not able to exact output.

public string Get(int id)
{
    if (G         


        
7条回答
  •  情话喂你
    2020-12-07 13:08

    QueryStringMapping` is nice solution but I need a default value for type.

    for xml : localhost:49533/api/?type=xml

    for json: localhost:49533/api/

    I solve that situation like that:

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    var jSettings = new JsonSerializerSettings();
    
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", new MediaTypeHeaderValue("application/xml")));
    

提交回复
热议问题