Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I've got an
IHttpActionResult
in "old" ASP.NET, which has the following code for
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
public async Task ExecuteResultAsync(ActionContext context)
I have two specific needs:
If _value is not null, send it back as the body of the response; and
If _uri is not null, send it back in the Location header of the response.
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.
How do you do it?
Yes, you definitely could use ObjectResponse for this case.
Regarding headers: in ExecuteResultAsync method you can directly modify the Response via context.HttpContext.Response property, so do something like this:
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);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.