Reputation:
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.
Upvotes: 36
Views: 86279
Reputation: 73
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
}
}
Upvotes: 0
Reputation: 484
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);
}
}
Upvotes: 0
Reputation: 1708
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" });
}
}
Upvotes: 2
Reputation: 598
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
Upvotes: 1
Reputation: 49779
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
Upvotes: 4
Reputation:
Finally I make a solution. :)
[HttpPost]
public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
Upvotes: 57