Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for Request.CreateResponse<List<string>>(HttpStatusCode.OK, messages)

I have been sending response in my api controller as following (.Net Framework 4.5)

 public virtual async Task<HttpResponseMessage> Import(Guid Id)
 { 
    ////
    return Request.CreateResponse<List<string>>(HttpStatusCode.OK, messages);
 }

What is the alternative for above in .NET Core 2.0?

I found a way new HttpResponseMessage(HttpStatusCode.Ok) but there is no constructor for HttpResponseMessage that takes / accept additional parameter for message.

So what i have option now?

like image 693
simbada Avatar asked Oct 22 '25 14:10

simbada


2 Answers

HttpResponseMessage is a legacy response object from classic ASP.NET WebAPI. It’s not used internally in ASP.NET Core and using it in your controller will only cause a compat layer to run to convert the legacy response type into what ASP.NET Core uses. So you should not use it when writing new code.

Instead, in ASP.NET Core, you return an IActionResult or for API methods the actual object the API endpoint returns.

The status code 200 OK is the default status code for requests, so you actually don’t need to explicitly return a response with that status code. In API controller actions, you can just return the actual object:

[HttpGet]
public List<string> GetMessages()
{
    var messages = GetMessagesFromService();

    return messages;
}

ASP.NET Core will automatically convert this into a proper response and convert the result to JSON (by default) and put it in the body. So you don’t need to create your response there.

If you find yourself in a situation where you need to change the status code, you can still do the same but just set the response’s status code before:

[HttpPost]
public string CreateMessage(string message)
{
    var message = CreateMessageInService(message);

    // set status code
    Response.StatusCode = 201; // 201 Created

    return message;
}

There are also a bunch of helper methods in ControllerBase that allow you to return explicit HTTP responses. For example Ok, Created, or NotFound. These method require a return type of IActionResult though, so you cannot use static typing with the method’s return type:

[HttpGet]
public IActionResult GetMessages()
{
    var messages = GetMessagesFromService();

    return Ok(messages);
}
like image 165
poke Avatar answered Oct 24 '25 04:10

poke


Your return type can be alternatively IHttpActionResult and from inside your method you could return Ok(messages)

like image 21
Dogu Arslan Avatar answered Oct 24 '25 06:10

Dogu Arslan