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

前端 未结 7 1848
佛祖请我去吃肉
佛祖请我去吃肉 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:28

    While the accepted answer by vijayjan15 seems the best way to go for your specific situation (that is, using the MediaTypeMappings), you could alternatively have two different methods, one that returns XML and one that returns JSON. To do that, you can instantiate a controller-specific HttpConfiguration (to avoid modifying the one in GlobalConfiguration.Configuration):

    public MyReturnType GetMyTypeAsXml() {
        Configuration = new HttpConfiguration();
        Configuration.Formatters.Clear();
        Configuration.Formatters.Add(new XmlMediaTypeFormatter());
    
        return new MyReturnType();
    }
    
    public MyReturnType GetMyTypeAsJson() {
        Configuration = new HttpConfiguration();
        Configuration.Formatters.Clear();
        Configuration.Formatters.Add(new JsonMediaTypeFormatter());
    
        return new MyReturnType();
    }
    

    I'm not sure how much overhead there is in spinning up a new instance of HttpConfiguration (I suspect not a lot), but the new instance comes with the Formatters collection filled by default, which is why you have to clear it right after instantiating it. Note that it if you don't use Configuration = new HttpConfiguration(), and instead modify Configuration directly, it modifies the GlobalConfiguration.Configuration property (so, it would impact all your other WebApi methods - bad!).

    0 讨论(0)
提交回复
热议问题