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


当前回答

一个快速的选择是使用MediaTypeMapping专门化。下面是一个在Application_Start事件中使用QueryStringMapping的例子:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("a", "b", "application/json"));

现在,只要url包含querystring(在这种情况下,a=b), Json响应就会显示在浏览器中。

其他回答

由于问题是chrome特定的,你可以得到邮递员扩展,它允许你设置请求内容类型。

在全球。我正在使用下面的代码。我获取JSON的URI是http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}

注意:阅读这个答案的注释,如果你使用WebAPI的默认错误处理,它可能会产生一个XSS漏洞

我只是在我的MVC Web API项目的App_Start / WebApiConfig.cs类中添加了以下内容。

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

这确保您在大多数查询中得到JSON,但当您发送text/ XML时可以得到XML。

如果你需要将响应Content-Type设置为application/json,请检查Todd下面的回答。

命名空间正在使用System.Net.Http.Headers。

如果你在WebApiConfig中这样做,默认情况下你会得到JSON,但是如果你传递text/ XML作为请求Accept头,它仍然允许你返回XML。

注意:这删除了对application/xml的支持

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

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

如果你不使用MVC项目类型,因此没有这个类开始,请参阅这个答案关于如何合并它的详细信息。

返回正确的格式是由媒体类型格式化程序完成的。 正如其他人提到的,你可以在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]。