C# 如何让WebAPI2返回JSON而不返回其他内容类型?

C# 如何让WebAPI2返回JSON而不返回其他内容类型?,c#,json,asp.net-web-api,http-error,C#,Json,Asp.net Web Api,Http Error,在最新的WebAPI2中,如何配置它,使其仅在Accept头为application/json时返回回复?此API仅支持json,如果发送了任何其他accept标头,则必须抛出错误。没有xml,甚至没有html接口 如果客户机请求xml或html或其他内容,我们需要抛出一个错误,让他们知道他们使用了错误的接受类型。当他们请求一个实际上不受支持的类型时,我们不能通过使用正确的json进行回复来掩盖这个问题 var request = (HttpWebRequest)WebRequest.Creat

在最新的WebAPI2中,如何配置它,使其仅在Accept头为application/json时返回回复?此API仅支持json,如果发送了任何其他accept标头,则必须抛出错误。没有xml,甚至没有html接口

如果客户机请求xml或html或其他内容,我们需要抛出一个错误,让他们知道他们使用了错误的接受类型。当他们请求一个实际上不受支持的类型时,我们不能通过使用正确的json进行回复来掩盖这个问题

var request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
var response = request.GetResponse();
并成功返回json结果。但是,如果存在任何其他Accept,则返回一个错误

var request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/xml"; // or text/html or text/plain or anything
var response = request.GetResponse();
返回HTTP 501未实现或类似的HTTP错误代码


这个问题不是重复的-这个问题问如何也返回json。我的问题是如何只返回json,并且只在客户端请求json时返回。如果客户端请求任何其他类型,如xml或html,则返回错误。

您可以清除除JSON以外的所有格式化程序:

configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());
或者,您可以更改默认Web API的内容协商机制:

public class JsonContentNegotiator : IContentNegotiator
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;

    public JsonContentNegotiator(JsonMediaTypeFormatter formatter) 
    {
        _jsonFormatter = formatter;    
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
        return result;
    }
}

// in app_start:

var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
并在app_start中注册:

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        config.MessageHandlers.Add(new FilterJsonHeaderHandler());
        // your other settings...
    }
}
注意:代码未经测试。如果有任何错误,请告诉我

显示如何直接访问内容协商。您可以将只包含所需格式的this.Configuration.Formatters的某些筛选子集传递给IContentNegotiator.Congregate,如下所示:

ContentNegotiationResult result = negotiator.Negotiate(
        typeof(Product), this.Request, this.Configuration.Formatters.Where(/* some expression that excludes all but the json formatter */);

这看起来相当笨拙,而且会有很多枯燥无味的样板文件,因此Javad_Amiry的答案可能更好,但这是另一个在特定情况下可能有用的选项。

除了使用不同的语言外,这可能是一个重复的选项?不,这个问题询问如何始终返回json,无论接受头是什么。我的问题是,如何仅在accept头为application/json时返回json,如果不是,则返回错误。当客户端使用accept:application/xml或accept:text/html请求时会发生什么?他们得到了json还是错误?如果是错误,是什么错误?我试过了,它返回了json内容类型:application/json,而accept是text/html
ContentNegotiationResult result = negotiator.Negotiate(
        typeof(Product), this.Request, this.Configuration.Formatters.Where(/* some expression that excludes all but the json formatter */);