Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi: Creating custom BadRequest status outside of ApiController

Using .NET Core 2.0 WebApi.

I have a webapi which has many endpoints where each endpoint is handling and throwing BadRequest when it fails. As below:

if(data == null)
{
   return BadRequest("Data must not be blank.");
}

Now since these status codes are repetitive in my api, I was thinking to create a Helper method which would return BadRequest back to my API.

So I created a static helper class. But the issue here is BadRequest is part of ControllerBase and is not available in my helper class. What is the best way to create this method that would return a BadRequest.

--Updated---

I want something like this:

    public static BadRequest GetBadRequestMessage(string message)
    {
        return BadRequest(message);
    }

I have also tried as:

    public static BadRequestResult GetBadRequestMessage(string message)
    {
        return new  BadRequestResult(message);
    }

But this gives error: Severity Code Description Project File Line Suppression State Error CS1729 'BadRequestResult' does not contain a constructor that takes 1 arguments

like image 344
user1563677 Avatar asked Aug 31 '18 17:08

user1563677


1 Answers

You can manually initialize the action result

return new BadRequestObjectResult("error message here");

Which is basically what the ControllerBase does internally

/// <summary>
/// Creates an <see cref="BadRequestResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <returns>The created <see cref="BadRequestResult"/> for the response.</returns>
[NonAction]
public virtual BadRequestResult BadRequest()
    => new BadRequestResult();

/// <summary>
/// Creates an <see cref="BadRequestObjectResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <param name="error">An error object to be returned to the client.</param>
/// <returns>The created <see cref="BadRequestObjectResult"/> for the response.</returns>
[NonAction]
public virtual BadRequestObjectResult BadRequest(object error)
    => new BadRequestObjectResult(error);

/// <summary>
/// Creates an <see cref="BadRequestObjectResult"/> that produces a <see cref="StatusCodes.Status400BadRequest"/> response.
/// </summary>
/// <param name="modelState">The <see cref="ModelStateDictionary" /> containing errors to be returned to the client.</param>
/// <returns>The created <see cref="BadRequestObjectResult"/> for the response.</returns>
[NonAction]
public virtual BadRequestObjectResult BadRequest(ModelStateDictionary modelState)
{
    if (modelState == null)
    {
        throw new ArgumentNullException(nameof(modelState));
    }

    return new BadRequestObjectResult(modelState);
}

Source

like image 78
Nkosi Avatar answered Nov 15 '22 20:11

Nkosi