asp.net核心中的Request.CreateResponse

时间:2017-01-20 06:16:28

标签: asp.net asp.net-core

下面是我的代码(部分代码),我想将其迁移到asp.net核心。 我的问题是“Request.CreateResponse”在下面的代码中不起作用。我谷歌很多,但无法找到任何解决方案。我该如何解决?软件包Microsoft.AspNet.WebApi.Core也无效。

    [HttpPost]
    public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
    {
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

提前致谢。

6 个答案:

答案 0 :(得分:19)

最后我提出了一个解决方案。 :)

[HttpPost]
public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
{
    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}

答案 1 :(得分:1)

如果您只想返回状态代码,请选择以下内容

//Creates a StatusCodeResult object by specifying a statusCode.
//so controller method should return IActionResult 
return StatusCode(HttpStatusCode.Unauthorized)

this SO answer

中查看详情

答案 2 :(得分:1)

对于Core 2.1+,返回ActionResult或IActionResult而不是HttpResponseMessage。这为您提供了难以置信的灵活性。下面是也返回内容的示例。

[HttpPost]
public ActionResult<BusinessUsers> AddBusinessUsersToBusinessUnit(MyObject request)
{   var businessUsers = AddBusinessUsers(request);
    return Request.CreateResponse(HttpStatusCode.Unauthorized, businessUsers);
}

https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.2

在Core 3.0中,必须使用ProducesResponseType确定所有可能的返回类型 https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.0

答案 3 :(得分:1)

试试这个,下面是示例 HTTP 获取控制器函数

   using System;
   using System.Net.Http;
   using System.Net;
   using System.Web.Http;
   using System.Threading.Tasks;
   using Newtonsoft.Json;
   using Newtonsoft.Json.Linq;

    [HttpGet]
    public async Task<ActionResult<string>> GetItem()
    {
        try
        {
            var Item = null;
            return JsonConvert.SerializeObject(Item);
        }
        catch (Exception ex)
        {
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            throw new System.Web.Http.HttpResponseException(response);
        }
    }

答案 4 :(得分:0)

最新版本无需返回Request.Create响应,而是返回OK以获得200个HTTP状态代码,并在响应中添加模型。 还返回IActionResult而不是HttpResponseMessage

public IActionResult Method()
{
  try
  {
     return Ok(new TokenResponseModel { Status = "ok", Message = "valid token" });
  }
}

答案 5 :(得分:0)

尝试类似的东西

public async Task<IActionResult> Method()
{
  try
  {
     var content = someCollectionReturnedFromDatabase();
     return Ok(content);
  }
  catch(Exception ex)
  {
    _logger.LogWarning(ex.Message, ex);
    return BadRequest(ex.Message); // this can be something like notfound
  }
}