2013-02-04 51 views
0

我創建了一個自定義分派器來處理使用客戶媒體類型的版本控制。它看起來是這樣的:如何將響應格式設置爲與請求相同的格式?

application/vnd.mycompany.myapi-v1+json 

的版本號,以便選擇正確的控制器提取大勢已去和工作,但作爲新的MVC的,我不知道如何設置響應格式。我們想要做的是設置響應格式以匹配請求。所以在這個例子中,響應將在json中。現在我假設我將不得不從這個內容類型中提取那個,這很好,但是有人可以給我一個例子,說明如何在MVC4中設置這個請求的響應格式,假設我已經創建了將會提取格式爲字符串?

private string GetResponseFormat(){ 
    //some shennanigans here 
} 

P.S.在請求期間沒有客戶端使用accept頭的原因是已經有客戶端使用我們的舊服務,它將設置accept頭以匹配請求。

回答

1

您還可以使用Content方法返回自定義響應類型:

string responseType = GetResponseFormat(); 
... 
switch(responseType){ 
    case "json": 
     string json = "yourJSON"; 
     return Content(json, "application/json"); 
    case "xml": 
     string xml = "yourXML"; 
     return Content(xml, "text/xml"); 
    default: 
     string plaintxt = "yourPlaintext"; 
     return Content(plaintxt, "text/plain"): 
} 
0

我能清除現有的接受頭,並添加到它:

private void SetResponseFormatToRequestFormat(HttpRequestMessage request) 
{ 
    // figure out what the request format was 
    _contentTypeHeader = request.Content.Headers.ContentType.ToString(); 
    if(_contentTypeHeader.Contains("xml")) _contentType = "application/xml"; 
    if (_contentTypeHeader.Contains("json")) _contentType = "application/json"; 

    // set response format to the same as the request format 
    request.Headers.Accept.Clear(); 
    request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(_contentType)); 
} 
相關問題