35

Below is my code (Partial code) and I want to migrate it into asp.net core. My problem is "Request.CreateResponse" is not working in below code. I google it a lot but unable to find any solution. How can I solve it? Package Microsoft.AspNet.WebApi.Core is also not working.

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

Thanks in advance.

6 Answers6

55

Finally I make a solution. :)

[HttpPost]
public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
{
    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
  • 31
    How would you add content to the response? – IeuanW Mar 13 '18 at 16:29
  • 4
    @IeuanW `ReasonPhrase` property – Shmil The Cat May 16 '18 at 14:25
  • 2
    @ShmilTheCat how will you add content other than string as ReasonPhrase is string type property? – lazydeveloper Aug 25 '18 at 17:25
  • 9
    @lazydeveloper Using Newtonsoft's Json.NET, and defining extension method: ```public static HttpResponseMessage CreateResponse(this HttpRequestMessage requestMessage, HttpStatusCode statusCode, T content) { return new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(JsonConvert.SerializeObject(content)) }; }``` – ps2goat Oct 25 '18 at 19:44
4

If you just want to return a status code, the following is preferable

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

See more in this SO answer

Community
  • 1
  • 1
Set
  • 47,577
  • 22
  • 132
  • 150
2

Instead of returning Request.Create Response, Latest version allows to return Ok for 200 http status code & add a model on your response if you want to Also Return IActionResult instead of HttpResponseMessage

public IActionResult Method()
{
  try
  {
     return Ok(new TokenResponseModel { Status = "ok", Message = "valid token" });
  }
}
NoloMokgosi
  • 1,678
  • 16
  • 10
  • 6
    While this code might answer the question, can you consider adding some explanation for what the problem was you solved, and how you solved it? This will help future readers to understand your answer better and learn from it. – Uwe Allner Feb 14 '20 at 10:04
1

For Core 2.1+, return ActionResult or IActionResult instead of HttpResponseMessage. This gives you incredible flexibility. Below is the example that also returns content back.

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

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

In Core 3.0, you must determine all possible return types with ProducesResponseType https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.0

Jason Honingford
  • 540
  • 5
  • 17
0

Try this out, below is sample HTTP get controller function

   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);
        }
    }
Varun
  • 422
  • 3
  • 14
0

Try something like that

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
  }
}
CredibleAshok
  • 73
  • 1
  • 9