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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With