简体   繁体   English

如何使用布尔值返回BadRequest?

[英]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. 我将它设置为返回一个布尔值,然后在前端(对控制器进行API调用)中设置了一个if / else if块来处理结果。

If the result is false, I want to throw a BadRequest so that I can present an error message to the user. 如果结果为假,我想抛出一个BadRequest,以便向用户显示错误消息。 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. 我以为也许可以在ActionResult中包装一个布尔值,但这似乎不起作用。 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). 它仅在返回true或false时才有效(我知道,它是一个布尔值,因此应该很明显,但是我认为ActionResult包装器可能会让我返回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. 您可以编写自定义的Authorization或Access装饰器([示例文档]) 1并返回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 最后: 使用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 请参阅ASP.NET Core Web API中的控制器动作返回类型

IActionResult type IActionResult类型

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. 如果一个动作中可能有多个ActionResult返回类型,则IActionResult返回类型是适当的。 The ActionResult types represent various HTTP status codes. ActionResult类型表示各种HTTP状态代码。 Some common return types falling into this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200). 属于此类别的一些常见返回类型是BadRequestResult (400), NotFoundResult (404)和OkObjectResult (200)。

Because there are multiple return types and paths in the action, liberal use of the [ProducesResponseType] attribute is necessary. 因为操作中有多个返回类型和路径,所以必须自由使用[ProducesResponseType]属性。 This attribute produces more descriptive response details for API help pages generated by tools like Swagger. 此属性为由Swagger之类的工具生成的API帮助页面生成更具描述性的响应详细信息。 [ProducesResponseType] indicates the known types and HTTP status codes to be returned by the action. [ProducesResponseType]指示该操作将返回的已知类型和HTTP状态代码。

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. 在前面的操作中,当基础数据存储区中不存在由id表示的产品时,将返回404状态代码。 The NotFound helper method is invoked as a shortcut to return new NotFoundResult(); 调用NotFound helper方法作为return new NotFoundResult();的快捷方式return new NotFoundResult(); . If the product does exist, a Product object representing the payload is returned with a 200 status code. 如果产品确实存在,则表示有效负载的Product对象将返回200状态代码。 The Ok helper method is invoked as the shorthand form of return new OkObjectResult(product); Ok helper方法被调用为return new OkObjectResult(product);的简写形式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 如果参数有效,您将收到状态码204 ,如果参数无效,您将收到状态码400(带有此json作为响应正文)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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