2012-10-11 6 views
0
받기

나는 다음과 같은 방법과 ApiController이 말?ApiController이 방법 응답 헤더

수동으로 응답을 생성하고 데이터를 직렬화해야한다고 생각하지만 어떻게해야합니까?

감사합니다.

+0

수정하려는 헤더는 무엇입니까? 무엇을 ? – Shyju

+0

@Shyju : ​​상관 없습니까? – Nick

+0

질문이 구체화/상세화 될수록 정답을 얻을 확률이 높아집니다. – Shyju

답변

4

을 대신 IEnumerable을 반환, 당신은 당신은 그것의 Headers 수정할 수 코드를 아래와 같이 HttpResponseMessage를 반환해야 예 : 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; 
} 
+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] 
public HttpResponseMessage GetSomeOfMyType() 
{ 
    var response = Request.CreateResponse(HttpStatusCode.OK, new MyType[10]); 

    //Access to header: response.Headers  

    return response; 
} 
+0

ASP.NET MVC 4를 사용하고 있습니다. HttpContext에 액세스 할 수있는 것 같지 않습니다. – Nick

+1

-1, 웹 API, MVC가 아님 –

+0

적어도 ASP.NET MVC 3에서는 Controller.HttpContext 속성을 통해 액세스 할 수있었습니다. MVC 3으로 작성된 프로젝트에서 실제로 사용하고 있습니다. http : // msdn .microsoft.com/ko-us/library/system.web.mvc.controller.httpcontext % 28v = vs.98 % 29.aspx –

0

:

[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 
    }; 
}