使用更新的ASP。NET Web API,在Chrome中我看到XML -我如何将其更改为请求JSON,以便我可以在浏览器中查看它?我相信这只是请求头的一部分,我是正确的吗?


当前回答

不要使用浏览器来测试API。

相反,尝试使用允许您指定请求的HTTP客户机,例如CURL,甚至Fiddler。

这个问题的问题在客户端,而不是API。web API根据浏览器的请求正确地工作。

其他回答

看看WebAPI中的内容协商。这些(第1部分和第2部分)非常详细和彻底的博客文章解释了它是如何工作的。

简而言之,您是对的,只需要设置Accept或Content-Type请求头。如果你的Action没有返回特定的格式,你可以设置Accept: application/json。

上面的大多数答案都很有道理。 由于您看到的数据是以XML格式格式化的,这意味着应用了XML格式化器,因此您可以通过从HttpConfiguration参数中删除XMLFormatter来查看JSON格式

public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );                
            config.Formatters.Remove(config.Formatters.XmlFormatter);                
            config.EnableSystemDiagnosticsTracing();
        }

因为JSON是默认格式

我不清楚为什么答案会这么复杂。当然,有很多方法可以做到这一点,QueryStrings,头和选项…但我认为最好的做法很简单。你请求一个简单的URL(例如:http://yourstartup.com/api/cars),作为回报,你得到JSON。你得到JSON和适当的响应头:

Content-Type: application/json

在寻找这个问题的答案时,我发现了这个帖子,并不得不继续下去,因为这个公认的答案并不完全正确。我确实找到了一个答案,我觉得它太简单了,不是最好的答案:

设置默认的WebAPI格式化程序

我把我的小费也加在这里。

WebApiConfig.cs

namespace com.yourstartup
{
  using ...;
  using System.Net.Http.Formatting;
  ...
  config.Formatters.Clear(); //because there are defaults of XML..
  config.Formatters.Add(new JsonMediaTypeFormatter());
}

我确实有一个问题,默认(至少我看到的那些)来自哪里。它们是. net默认的,还是在其他地方创建的(由我项目中的其他人创建)。无论如何,希望这能有所帮助。

返回正确的格式是由媒体类型格式化程序完成的。 正如其他人提到的,你可以在WebApiConfig类中做到这一点:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        // Configure Web API to return JSON
        config.Formatters.JsonFormatter
        .SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

        ...
    }
}

欲了解更多信息,请查看:

ASP中的媒体格式化器。NET Web API ASP中的内容协商。NET Web API。

如果您的操作返回XML(这是默认情况),并且您只需要一个特定的方法来返回JSON,那么您可以使用ActionFilterAttribute并将其应用于特定的操作。

过滤器属性:

public class JsonOutputAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
        var value = content.Value;
        Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];

        var httpResponseMsg = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            RequestMessage = actionExecutedContext.Request,
            Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
        };

        actionExecutedContext.Response = httpResponseMsg;
        base.OnActionExecuted(actionExecutedContext);
    }
}

适用于行动:

[JsonOutput]
public IEnumerable<Person> GetPersons()
{
    return _repository.AllPersons(); // the returned output will be in JSON
}

注意,您可以省略动作修饰上的Attribute这个词,只使用[JsonOutput]而不是[JsonOutputAttribute]。

在最近更新了核心库和Json之后,多年来一直使用Felipe Leusin的答案。Net,我遇到了System.MissingMethodException:SupportedMediaTypes。 在我的案例中,解决方案是安装System.Net.Http,希望对遇到同样意外异常的其他人有所帮助。NuGet显然会在某些情况下删除它。手动安装后,该问题得到了解决。