2012-10-11 51 views
0

說我有以下方法的ApiControllerApiController GET方法響應頭

[HttpGet] 
IEnumerable<MyType> GetSomeOfMyType() 
{ 
    return new MyType[ 10 ]; 
} 

我要修改的響應報頭中的一個,我將如何去轉換這種方法允許?

我猜我需要手動創建一個響應並將我的數據串入到它中,但是如何?

謝謝。

+0

要修改哪個頭?什麼? – Shyju

+0

@Shyju:重要嗎? – Nick

+0

問題越具體/詳細,獲得正確答案的機會越多 – Shyju

回答

4

,而不是返回IEnumerable,你應該返回HttpResponseMessage像下面的代碼,那麼你可以修改其Headers

[HttpGet] 
public HttpResponseMessage GetSomeOfMyType() 
{ 
    var response = Request.CreateResponse(HttpStatusCode.OK, new MyType[10]); 

    //Access to header: response.Headers  

    return response; 
} 
+0

實際情況是我正在將'HttpResponseMessage'傳遞給我的函數,因此我不得不使用'HttpResponse.CreateContent()'方法。但是這指出了我正確的方向(並回答了我問的問題!) – Nick

-1
[HttpGet] 
ActionResult GetSomeOfMyType() 
{ 
    ... 
    HttpContext.Response.AppendHeader("your_header_name", "your_header_value"); 
    ... 

    return Json(new MyType[ 10 ]); 
} 

假設您使用JSON進行序列化。否則,你可以使用ContentResult類和自定義序列化功能,如:

[HttpGet] 
ActionResult GetSomeOfMyType() 
{ 
    ... 
    HttpContext.Response.AppendHeader("your_header_name", "your_header_value"); 
    ... 

    return new ContentResult { 
     Content = YourSerializationFunction(new MyType[ 10 ]), 
     ContentEncoding = your_encoding, // optional 
     ContentType = "your_content_type" // optional 
    }; 
} 
+0

我正在使用ASP.NET MVC 4.我似乎沒有訪問HttpContext。 – Nick

+1

-1,它是用於Web Api,而不是用於MVC –

+0

它可以通過Controller.HttpContext屬性至少在ASP.NET MVC 3中訪問 - 我實際上在我的項目中使用MVC 3編寫的代碼:http:// msdn .microsoft.com/en-us/library/system.web.mvc.controller.httpcontext%28v = vs.98%29.aspx –

0

這裏的來自asp.net的一個示例:

public HttpResponseMessage PostProduct(Product item) 
{ 
    item = repository.Add(item); 
    var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item); 

    string uri = Url.Link("DefaultApi", new { id = item.Id }); 
    response.Headers.Location = new Uri(uri); 
    return response; 
}