简体   繁体   中英

How to get around HttpResponseMessage (Request.CreateResponse) in .net Core

protected HttpResponseMessage CreatedResponse(string routeName, object routeValues)
{
    var response = Request.CreateResponse(HttpStatusCode.Created);
    var locationUri = Url.Link(routeName, routeValues);
    response.Headers.Location = new Uri(locationUri);

    return response;
}

Whats the equivalent code in .net Core? Or a way around it..

Thanks

you need to use Controller.Created method, but now it also requires information about URI:

public IActionResult CreatedResponse(object value)
{
     return this.Created(<string uri>, value);
     //or 
     return this.Created(<Uri uri>, value);
}

Actually, in background method creates and returns the CreatedResult object, that is derived from ObjectResult , and fill Location , Value and StatusCode fields. So, as alternative, you may create general ObjectResult response if you don't need to return the URI.

public IActionResult CreatedResponse(object value)
{
    return new ObjectResult
    {
        Value = value,
        StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status201Created // 201
    };
}

I built upon the other answer, and created an extension method. You will have to return an IActionResult. So if you still want to do it the old fashion way, you can with this:

public static class HttpRequestExtensions
{
  public static IActionResult CreateResponse(this HttpRequest request, int status, object content)
  {
    return new ObjectResult(content)
    {
      StatusCode = status
    };
  }
}

And in use:

public IActionResult Patch(long id, [FromBody]JsonPatchDocument<SomeModel> value)
{
  //other code here for patching logic

  var response = new { Original = modelBefore, Patched = modelAfter };

  return Request.CreateResponse(StatusCodes.Status200OK, response);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM