Home > Back-end >  .net API post returns an object but want to override object and return a HTTP error code with descri
.net API post returns an object but want to override object and return a HTTP error code with descri

Time:01-31

I am receiving a post which if successfully locating data will fill and return an object named "ClientLoginOut"

[AllowAnonymous]
[HttpPost]
public ClientLoginOut Post(ClientLogin clientlogin)

This works fine.

But if there is a problem looking up the data, I would like to return a Server response : 400 with a message in json formatted message.

This is what I would like to return

{
    "errorMessage": "Login Invalid"
}

I tried a return using the following

HttpResponseMessage message = Request.CreateResponse(HttpStatusCode.BadRequest, "Login Invalid");
return message;

But the compiler is giving this error on the "return message;" line

Severity    Code    Description Project File    Line    Suppression State

Error CS0029 Cannot implicitly convert type 'System.Net.Http.HttpResponseMessage' to 'Models.ClientLoginOut' APIApp C:\inetpub\wwwroot\APIApp\Controllers\ClientLoginController.cs 165 Active

How can I override the "ClientLoginOut" object and return a custom error code with custom message?

CodePudding user response:

You can throw a HttpResponseException with a HttpResponseMessage as the parameter, containing the error status code and message:

if (data lookup fails)
{
    var errorMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
        Content = new StringContent("{\"errorMessage\": \"Login Invalid\"}", System.Text.Encoding.UTF8, "application/json")
    };
    throw new HttpResponseException(errorMessage);
}

UPDATED ANSWER BELOW: Instead, you can use ProblemDetails to return a structured response that includes error information. This can be done by creating an instance of the ProblemDetails class, setting its properties, and returning it as the result of the action method.

Here's an example of how you can return a ProblemDetails response:

[HttpGet]
public IActionResult GetData()
{
    var problemDetails = new ProblemDetails
    {
        Title = "An error occurred",
        Detail = "Login Invalid",
        Status = 400
    };
    return BadRequest(problemDetails);
}
public class ProblemDetails
{
    public string Type { get; set; }
    public string Title { get; set; }
    public int Status { get; set; }
    public string Detail { get; set; }
    public string Instance { get; set; }
}

CodePudding user response:

Just set your controller method return type to HttpResponseMessage and return it:

 [AllowAnonymous]
 [HttpPost]
 public HttpResponseMessage Post([FromBody] ClientLogin clientlogin)
 {
        // .... handle non-error situations, OR
        return new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent(jsonSerializedErrorResponse, System.Text.Encoding.UTF8, "application/json")
        };
 }

(don't forget FromBody this always burns me)

  • Related