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

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


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation