2013-10-30 30 views
5

我已经实现了自定义媒体格式器,并且在客户端明确请求“csv”格式时它工作得很好。为WebAPI操作设置默认媒体格式化器

我过我的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处理程序。如何配置Controller的端点以使其默认返回CSV,并且只在客户端请求时才返回JSON/XML?

回答

0

您正在使用哪个版本的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; 
}