36

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 Answers 6

57

Finally I make a solution. :)

[HttpPost]
public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
{
    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
Sign up to request clarification or add additional context in comments.

4 Comments

How would you add content to the response?
@IeuanW ReasonPhrase property
@ShmilTheCat how will you add content other than string as ReasonPhrase is string type property?
@lazydeveloper Using Newtonsoft's Json.NET, and defining extension method: public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage requestMessage, HttpStatusCode statusCode, T content) { return new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(JsonConvert.SerializeObject(content)) }; }
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

Comments

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" });
  }
}

1 Comment

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.
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

1 Comment

@HaithemKAROUI Thanks I updated the answer to include ProducesResponseType for those using Core 3.0.
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);
        }
    }

Comments

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
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.