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

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

    What you are trying to do will not work in a multi-threaded environment. You cannot add to and remove from the formatters collection on a per-request basis. Here is a better way of accomplishing what you want.

    public HttpResponseMessage Get(int id)
    {
        Foo foo = new Foo();
        var content = new ObjectContent(foo,
                        ((id == 1) ? Configuration.Formatters.XmlFormatter :
                                    Configuration.Formatters.JsonFormatter));
        return new HttpResponseMessage()
        {
             Content = content
        };
    }
    

提交回复
热议问题