0

In a WebApi2 project I could create a custom action response a bit like this:

public class TestResult : IHttpActionResult
{
    private readonly int id;

    public TestResult (int id)
    {
        this.id = id;
    }

    public Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        var response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.Accepted; 
        response.Headers.Location = new Uri($"xxx\{id}");
        response.Content = new ObjectContent<Test>(new Test { TestNumber = id }, mediaType));
        return response;
    }
}

This sets the response content and location on the header.

How do I do this in .Net core?

The IActionResult result interface only has 1 method:
Task ExecuteResultAsync(ActionContext context)

Thanks

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Sun
  • 4,458
  • 14
  • 66
  • 108
  • Have you tried inheriting from `ObjectResult`? You can pass a value and override the default behavior, then calling the base `ExecuteResultAsync` – ColinM Oct 12 '20 at 14:45
  • 2
    Does this answer your question? [How to write custom actionResult in asp.net core](https://stackoverflow.com/questions/42594356/how-to-write-custom-actionresult-in-asp-net-core) – Peter Csala Oct 12 '20 at 14:50
  • @PeterCsala No it doesn't as that doesn't set the location and I don't seem to have that option – Sun Oct 12 '20 at 14:54
  • @ColinM How to set the location though? – Sun Oct 12 '20 at 14:55
  • @Sun you set the Location header, via `actionContext.HttpContext.Response.Headers` dictionary, within the `ExecuteResultAsync` method. – ColinM Oct 12 '20 at 15:36
  • @ColinM Thank you – Sun Oct 12 '20 at 19:48

0 Answers0