How do I get ASP.NET Web API to return JSON instea

2018-12-31 03:44发布

Using the newer ASP.NET Web API, in Chrome I am seeing XML - how can I change it to request JSON so I can view it in the browser? I do believe it is just part of the request headers, am I correct in that?

29条回答
只若初见
2楼-- · 2018-12-31 04:38

I like Felipe Leusin's approach best - make sure browsers get JSON without compromising content negotiation from clients that actually want XML. The only missing piece for me was that the response headers still contained content-type: text/html. Why was that a problem? Because I use the JSON Formatter Chrome extension, which inspects content-type, and I don't get the pretty formatting I'm used to. I fixed that with a simple custom formatter that accepts text/html requests and returns application/json responses:

public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
    public BrowserJsonFormatter() {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        this.SerializerSettings.Formatting = Formatting.Indented;
    }

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
}

Register like so:

config.Formatters.Add(new BrowserJsonFormatter());
查看更多
还给你的自由
3楼-- · 2018-12-31 04:39

As the question is Chrome-specific, you can get the Postman extension which allows you to set the request content type.

Postman

查看更多
只若初见
4楼-- · 2018-12-31 04:39

Don't use your browser to test your API.

Instead, try to use an HTTP client that allows you to specify your request, such as CURL, or even Fiddler.

The problem with this issue is in the client, not in the API. The web API behaves correctly, according to the browser's request.

查看更多
冷夜・残月
5楼-- · 2018-12-31 04:40

This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true.

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Thanks everyone!

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 04:40
        config.Formatters.Remove(config.Formatters.XmlFormatter);
查看更多
还给你的自由
7楼-- · 2018-12-31 04:41

I just add the following in App_Start / WebApiConfig.cs class in my MVC Web API project.

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );

That makes sure you get json on most queries, but you can get xml when you send text/xml.

If you need to have the response Content-Type as application/json please check Todd's answer below.

NameSpace is using System.Net.Http.Headers;

查看更多
登录 后发表回答