How to force ASP.NET Web API to return JSON or XML

2020-02-02 04:17发布

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 (GlobalConfiguration.Configuration.Formatters.XmlFormatter == null)
    {
        GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
    }
    if (GlobalConfiguration.Configuration.Formatters.JsonFormatter == null)
    {
        GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
    }
    if (id == 1)
    {
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter);                
        GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;                
    }
    else
    {
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
    }
    return "value";
}

7条回答
看我几分像从前
2楼-- · 2020-02-02 05:00

It also works to force the accept headers. Great option if you aren't always returning HttpResponseMessage's. I.e

Request.Headers.Add("Accept", "text/json");
return Request.CreateResponse(HttpStatusCode.OK, yourobject);

or

Request.Headers.Add("Accept", "application/xml");
return new Rss20FeedFormatter(feed);
查看更多
登录 后发表回答