asp.net - 为 Web API 操作设置默认媒体格式化程序

标签 asp.net json asp.net-mvc-4 csv asp.net-web-api

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

我已经使用以下代码测试了我的 api Controller :

        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 处理程序。如何配置 Controller 的端点,使其默认返回 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);
}

如果您正在使用 4.0 版本的 Web API,那么您可以执行以下操作:
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;
}

关于asp.net - 为 Web API 操作设置默认媒体格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687815/

相关文章:

c# - 在 mvc4 中创建通用 mvc View

c# - 哪种设计模式用于过滤查询? C#

javascript - 客户端接收json对象到javascript

javascript - 当我将 C# 行添加到 View Razor 页面中的 JavaScript 代码时出现 ReferenceError

javascript - 如何动态决定并告诉 d3.json() 函数何时采用哪个 json

javascript - 如何在 React Native 中访问 json 对象的字符串

c# - 找不到“AllowAnonymous”

c# - 在没有页面的情况下使用 LoadControl

c# - 如何使用嵌套中继器获取代码后面的页脚项值?

asp.net - 如何获取 JSON 字符串化数据