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;
}
.net Core中的等效代码是什么? 或者绕过它......
由于
答案 0 :(得分:1)
您需要使用Controller.Created
方法,但现在它还需要有关URI的信息:
public IActionResult CreatedResponse(object value)
{
return this.Created(<string uri>, value);
//or
return this.Created(<Uri uri>, value);
}
实际上,在background方法中创建并返回CreatedResult对象,该对象派生自ObjectResult
,并填充Location
,Value
和StatusCode
字段。因此,如果您不需要返回URI,则可以创建一般ObjectResult
响应。
public IActionResult CreatedResponse(object value)
{
return new ObjectResult
{
Value = value,
StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status201Created // 201
};
}
答案 1 :(得分:0)
我建立在另一个答案的基础上,并创建了一个扩展方法。您将不得不返回IActionResult。因此,如果您仍然希望以旧式方式进行,您可以使用:
public static class HttpRequestExtensions
{
public static IActionResult CreateResponse(this HttpRequest request, int status, object content)
{
return new ObjectResult(content)
{
StatusCode = status
};
}
}
并在使用中:
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);
}