0

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:

  1. If _value is not null, send it back as the body of the response; and
  2. 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?

McGuireV10
  • 9,572
  • 5
  • 48
  • 64
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387

1 Answers1

2

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);
}
Set
  • 47,577
  • 22
  • 132
  • 150