Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request.CreateResponse in asp.net core

People also ask

What are the methods that create HttpResponseMessage with request?

CreateResponse<T>(HttpRequestMessage, HttpStatusCode, T, MediaTypeFormatter) Helper method that creates a HttpResponseMessage with an System.

How do I set HttpResponseMessage content?

Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore. Now, you need to use the Content property to set the content of the message.

What is IHttpActionResult?

The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface: Simplifies unit testing your controllers. Moves common logic for creating HTTP responses into separate classes.

What is OkObjectResult?

Ok(object) is a controller method that returns a new OkObjectResult(object); the OkResult class implements an ActionResult that produces an empty 200 response. the OkObjectResult class implements an ActionResult that process a 200 response with a body based on the passed object.


Finally I make a solution. :)

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

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


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

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