gpt4 book ai didi

c# - WebAPI : Creating custom BadRequest status outside of ApiController

转载 作者:太空狗 更新时间:2023-10-29 23:19:59 24 4
gpt4 key购买 nike

使用 .NET Core 2.0 WebApi。

我有一个 webapi,它有许多端点,每个端点都在处理并在失败时抛出 BadRequest。如下:

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

现在,由于这些状态代码在我的 API 中重复出现,我正在考虑创建一个 Helper 方法,它将 BadRequest 返回给我的 API。

所以我创建了一个静态助手类。但这里的问题是 BadRequest 是 ControllerBase 的一部分,在我的助手类中不可用。创建此返回 BadRequest 的方法的最佳方法是什么。

--已更新---

我想要这样的东西:

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

我也试过:

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

但这会产生错误:严重性代码描述项目文件行抑制状态错误 CS1729“BadRequestResult”不包含采用 1 个参数的构造函数

最佳答案

可以手动初始化 Action 结果

return new BadRequestObjectResult("error message here");

这基本上就是 ControllerBase 内部所做的事情

/// <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

关于c# - WebAPI : Creating custom BadRequest status outside of ApiController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52120295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com