[英]How to translate this IHttpActionResult to ASP.NET Core IActionResult
I've got an IHttpActionResult
in "old" ASP.NET, which has the following code for ExecuteAsync
: 我在“旧的” ASP.NET中有一个
IHttpActionResult
,它具有ExecuteAsync
的以下代码:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _value == null ?
_request.CreateResponse(StatusCode) :
_request.CreateResponse(StatusCode, _value);
if (_uri != null)
{
var relativeUri = new Uri(_uri.PathAndQuery, UriKind.Relative);
response.Headers.Location = relativeUri;
}
return Task.FromResult(response);
}
Now, to translate this to the ASP.NET Core IActionResult
, I realize that I need to change the signature to 现在,要将其转换为ASP.NET Core
IActionResult
,我意识到我需要将签名更改为
public async Task ExecuteResultAsync(ActionContext context)
I have two specific needs: 我有两个特定需求:
_value
is not null, send it back as the body of the response; _value
不为null,则将其作为响应的正文发送回; and _uri
is not null, send it back in the Location
header of the response. _uri
不为null,则将其发送回响应的Location
标头中。 I've found lots of similar questions, like this , which suggests manipulating the context
's Response
property - but this doesn't answer how to set the body for an object
(rather than a string), or this , which suggests using an ObjectResponse
, but it isn't clear to me how I would add the required header. 我发现了很多类似的问题,例如this ,它建议操作
context
的Response
属性-但这不能回答如何为object
(而不是字符串)设置主体,或者this ,它建议使用ObjectResponse
,但是我不清楚如何添加所需的标头。
How do you do it? 你怎么做呢?
Yes, you definitely could use ObjectResponse
for this case. 是的,您肯定可以在这种情况下使用
ObjectResponse
。
Regarding headers: in ExecuteResultAsync
method you can directly modify the Response via context.HttpContext.Response
property, so do something like this: 关于标题:在
ExecuteResultAsync
方法中,您可以通过context.HttpContext.Response
属性直接修改Response,因此可以执行以下操作:
public async Task ExecuteResultAsync(ActionContext context)
{
// note: ObjectResult allows to pass null in ctor
var objectResult = new ObjectResult(_value)
{
StatusCode = <needed status_code>
};
context.HttpContext.Response.Headers["Location"] = "<your relativeUri>";
await objectResult.ExecuteResultAsync(context);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.