0

私がApiController次の方法で持っているとしましょう:

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

そして、応答ヘッダーの1つを変更したいのですが、それを可能にするためにこのメソッドを変換するにはどうすればよいですか?

手動で応答を作成し、それにデータをシリアル化する必要があると思いますが、どうすればよいですか?

ありがとう。

4

3 に答える 3

4

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;
}
于 2012-10-11T15:30:08.543 に答える
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;
}
于 2012-10-11T18:36:47.863 に答える
-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
    };
}
于 2012-10-11T15:18:19.360 に答える