2013-10-30 52 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; 
}