Home > other >  Asp.net Core 3.1 Web Api return custom error message from IActionResult
Asp.net Core 3.1 Web Api return custom error message from IActionResult

Time:03-15

Is it possible to return custom error messages to client from Asp.Net Core 3.1 Web Api? I've tried a few different things to set the "ReasonPhrase" with no luck. I have tried using StatusCode:

return StatusCode(406, "Employee already exists");

I tried to return using HttpResponseMessage:

    HttpResponseMessage msg = new HttpResponseMessage();
    msg.StatusCode = HttpStatusCode.NotAcceptable;
    msg.ReasonPhrase = "Employee alredy exists";
    return (IActionResult)msg;

I am trying to return a message to the client calling the method that the employee already exists:

    public async Task<IActionResult> CreateEmployee([FromBody] EmployeeImport Employee)
    {
        var exists = await employeeService.CheckForExistingEmployee(Employee);
        if (exists > 0)
        {

            //return StatusCode(406, "Employee already exists");
            HttpResponseMessage msg = new HttpResponseMessage();
            msg.StatusCode = HttpStatusCode.NotAcceptable;
            msg.ReasonPhrase = "Employee already exists";
            return (IActionResult)msg;
        }
    }

This is the code in the client:

    public async Task<ActionResult>AddEmployee(EmployeeImport employee)
    {
        var message = await CommonClient.AddEmployee(employee);
        return Json(message.ReasonPhrase, JsonRequestBehavior.AllowGet);

    }
    public async Task<HttpResponseMessage> AddEmployee(EmployeeImport employee)
    {
        var param = Newtonsoft.Json.JsonConvert.SerializeObject(employee);
        HttpContent contentPost = new StringContent(param, System.Text.Encoding.UTF8, "application/json");
        var response = await PerformPostAsync("entity/NewEmployee", contentPost);
        return response;
    }
    protected async Task<HttpResponseMessage> PerformPostAsync(string requestUri, HttpContent c)
    {
        _webApiClient = new HttpClient { BaseAddress = _baseAddress };
        _webApiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
        var webApiResponse = await _webApiClient.PostAsync(requestUri, c);
        return webApiResponse;

    }

CodePudding user response:

To do this, you can create a Custom Error class that implements the IActionResult interface as follows:

 public class CustomError : IActionResult
{
    private readonly HttpStatusCode _status;
    private readonly string _errorMessage;

    public CustomError(HttpStatusCode status, string errorMessage)
    {
        _status = status;
        _errorMessage = errorMessage;
    }
    public async Task ExecuteResultAsync(ActionContext context)
    {
        var objectResult = new ObjectResult(new
        {
            errorMessage = _errorMessage
        })
        {
            StatusCode = (int)_status,

        };

      context.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = _errorMessage;
      
      await objectResult.ExecuteResultAsync(context);

    }
}

And use the following form :

[HttpGet]
public IActionResult GetEmployee()
{
   return new CustomError(HttpStatusCode.NotFound, "The employee was not found");
}

CodePudding user response:

Try changing

return (IActionResult)msg;

to

return Task.FromResult(BadRequest(msg) as IActionResult);
  • Related