Asp.net 为WebAPI操作设置默认媒体格式化程序

Asp.net 为WebAPI操作设置默认媒体格式化程序,asp.net,json,asp.net-mvc-4,csv,asp.net-web-api,Asp.net,Json,Asp.net Mvc 4,Csv,Asp.net Web Api,我已经实现了一个自定义媒体格式化程序,当客户端特别要求“csv”格式时,它工作得非常好 我已经用以下代码测试了我的api控制器: HttpClient client = new HttpClient(); // Add the Accept header client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv")); 但是,当我从w

我已经实现了一个自定义媒体格式化程序,当客户端特别要求“csv”格式时,它工作得非常好

我已经用以下代码测试了我的api控制器:

        HttpClient client = new HttpClient();
        // Add the Accept header
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));

但是,当我从web浏览器打开相同的URL时,它返回的是JSON而不是CSV。这可能是由于标准ASP.NET WebAPI配置将JSON设置为默认媒体格式化程序,除非调用方另有指定。我希望在我拥有的所有其他web服务上都使用此默认行为,但在返回CSV的单个操作上不使用此默认行为。我希望默认的媒体处理程序是我实现的CSV处理程序。如何配置控制器的端点,使其在默认情况下返回CSV,并且仅在客户端请求时返回JSON/XML?

您使用的是哪个版本的Web API

如果您使用的是
5.0
版本,则可以使用新的基于
IHttpActionResult
的逻辑,如下所示:

public IHttpActionResult Get()
{
    MyData someData = new MyData();

    // creating a new list here as I would like CSVFormatter to come first. This way the DefaultContentNegotiator
    // will behave as before where it can consider CSVFormatter to be the default one.
    List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
    respFormatters.Add(new MyCsvFormatter());
    respFormatters.AddRange(Configuration.Formatters);

    return new NegotiatedContentResult<MyData>(HttpStatusCode.OK, someData,
                    Configuration.Services.GetContentNegotiator(), Request, respFormatters);
}
public HttpResponseMessage Get()
{
    MyData someData = new MyData();

    HttpResponseMessage response = new HttpResponseMessage();

    List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
    respFormatters.Add(new MyCsvFormatter());
    respFormatters.AddRange(Configuration.Formatters);

    IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
    ContentNegotiationResult negotiationResult = negotiator.Negotiate(typeof(MyData), Request, respFormatters);

    if (negotiationResult.Formatter == null)
    {
        response.StatusCode = HttpStatusCode.NotAcceptable;
        return response;
    }

    response.Content = new ObjectContent<MyData>(someData, negotiationResult.Formatter, negotiationResult.MediaType);

    return response;
}