简体   繁体   中英

How to return a BadRequest with a boolean?

I have a controller method that I'm using to validate a token. I have it set up to return a boolean value and then on the front end, which makes an API call into the controller, I have an if/else if block set up to handle the result.

If the result is false, I want to throw a BadRequest so that I can present an error message to the user. I really want this handled on the back end rather than on the front end. I thought maybe I could wrap a boolean in an ActionResult, but that doesn't seem to be working. It only works when I return either a true or a false (I know, it's a boolean, so that should be obvious, but I thought the ActionResult wrapper might let me return a BadRequest).

Any advice on how I can do this?

public async Task<ActionResult<bool>> ValidateStuff(params)
{
    return BadRequest("BAD REQUEST!");
}

Don't!

If you want to handle that, then it's fine. But don't return the wrong error code.

You can write custom Authorization or Access decorators ([example documentation]) 1 and return a 401.

Don't arbitrarily return a code that doesn't equal the problem though, these standards are well defined and understood.

And finally: Another example using HttpResponse

 var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
 throw new HttpResponseException(msg);

It is documented how to handle different return types.

See Controller action return types in ASP.NET Core Web API

IActionResult type

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Some common return types falling into this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200).

Because there are multiple return types and paths in the action, liberal use of the [ProducesResponseType] attribute is necessary. This attribute produces more descriptive response details for API help pages generated by tools like Swagger. [ProducesResponseType] indicates the known types and HTTP status codes to be returned by the action.

Synchronous action

Consider the following synchronous action in which there are two possible return types:

 [HttpGet("{id}")] [ProducesResponseType(typeof(Product), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public IActionResult GetById(int id) { if (!_repository.TryGetProduct(id, out var product)) { return NotFound(); } return Ok(product); } 

In the preceding action, a 404 status code is returned when the product represented by id doesn't exist in the underlying data store. The NotFound helper method is invoked as a shortcut to return new NotFoundResult(); . If the product does exist, a Product object representing the payload is returned with a 200 status code. The Ok helper method is invoked as the shorthand form of return new OkObjectResult(product); .

But in your case I would not return any value, because the status code already contains enough information.

[HttpPost]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ValidateStuff(params)
{
    if ( !await ValidateAsync(params) )
        return ValidationProblem( 
            new ValidationProblemDetails 
            { 
                Detail = "params are invalid" 
            } );

    return NoContent();
}

If params are valid you will receive the status code 204 and in case of invalid params you will receive the status code 400 with this json as response body

{
  "errors": {},
  "type": null,
  "title": "One or more validation errors occurred.",
  "status": 400,
  "detail": "params are invalid",
  "instance": null,
  "extensions": {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM