我们如何通过StatusCodeResult 202接受响应返回位置标头?

时间:2018-05-16 12:53:52

标签: asp.net-mvc asp.net-web-api

我们正在使用StatusCodeResult来获取来自API的202接受响应,但还需要返回位置标头。我们怎样才能做到这一点?这是我们目前的代码:

:

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

var response = Request.CreateResponse(HttpStatusCode.Accepted);
response.Headers.Location = Request.RequestUri;

答案 1 :(得分:2)

您可以在设置标题的位置创建自定义IHttpActionResult实现:

public class StatusCodeWithLocationResult : IHttpActionResult
{
    private readonly StatusCodeResult _result;
    private readonly Uri _location;

    public StatusCodeWithLocationResult(StatusCodeResult result, Uri location)
    {
        _result = result;
        _location = location;
    }

    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = await _result.ExecuteAsync(cancellationToken).ConfigureAwait(false);
        response.Headers.Location = _location;
        return response;
    }
}

然后使用它:

return new StatusCodeWithLocationResult(StatusCode(HttpStatusCode.Accepted), myUri);