私がApiController
次の方法で持っているとしましょう:
[HttpGet]
IEnumerable<MyType> GetSomeOfMyType( )
{
return new MyType[ 10 ];
}
そして、応答ヘッダーの1つを変更したいのですが、それを可能にするためにこのメソッドを変換するにはどうすればよいですか?
手動で応答を作成し、それにデータをシリアル化する必要があると思いますが、どうすればよいですか?
ありがとう。
私がApiController
次の方法で持っているとしましょう:
[HttpGet]
IEnumerable<MyType> GetSomeOfMyType( )
{
return new MyType[ 10 ];
}
そして、応答ヘッダーの1つを変更したいのですが、それを可能にするためにこのメソッドを変換するにはどうすればよいですか?
手動で応答を作成し、それにデータをシリアル化する必要があると思いますが、どうすればよいですか?
ありがとう。
Instead of returning IEnumerable
, you should return HttpResponseMessage
like below code, then you can modify its Headers
:
[HttpGet]
public HttpResponseMessage GetSomeOfMyType( )
{
var response = Request.CreateResponse(HttpStatusCode.OK, new MyType[10]);
//Access to header: response.Headers
return response;
}
これが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;
}
[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
};
}