【问题标题】:ASP.NET WebApi return different object on exceptionASP.NET WebApi 在异常时返回不同的对象
【发布时间】:2021-05-27 15:29:03
【问题描述】:

我目前正在开发一个API,需要为该api返回一些对象或者在某处失败的情况下返回错误,主要是因为我依赖于数据库调用。

这是我的一些代码:

    public Student GetStudent(string parametr)
    {
        try
        {
            // Database call 1
            // Database call 2
            return new Student();
        }
        catch (Exception ex)
        {
            // return new ErrorDetails(ex.message); -- example
            return null;
        }
    }

我的一个限制是我需要大摇大摆地使用这个 API。我尝试使用 HttpResponse ,它完全符合我对编码部分的需求,但这不适用于招摇。我的 Web 应用程序不是 asp.net 核心。

对我应该怎么做有什么想法或建议吗?

提前致谢,

【问题讨论】:

  • 根据异常情况,您应该返回适​​当的 http 状态(如 400 或 409 或 500)以及一般错误,具体取决于错误的原因/来源。至于如何在您的 api 中执行此操作,我将搜索“Swagger 如何返回 http 状态代码”
  • 您能否详细说明一下 HttpResponse 在 Swagger 中不适合您,因为它不是 ASP.NET Core 应用程序?它应该工作。什么具体不适用于您的情况?

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

您可以使用 Swagger DataAnnotations 并封装返回数据来实现这一点

首先创建一个类来封装这样的错误消息

public class Errors
{
    public List<string> ErrorMessages { get; set; } = new List<string>();
}

然后使用这样的注释

适用于 .NET 4.5+(全框架)

[SwaggerResponse(HttpStatusCode.OK, Type = typeof(Student))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(Errors))];
public IHttpActionResult GetStudent(string parametr)
{
    try
    {
        // Database call 1
        // Database call 2
        return Ok(new Student());
    }
    catch (Exception ex)
    {
        Errors errors = new Errors();
        errors.ErrorMessages.Add(ex.Message);

        return Content(HttpStatusCode.BadRequest, errors);
    }
}

对于 .NET Core

[ProducesResponseType(200, Type = typeof(Student))]
[ProducesResponseType(400, Type = typeof(Errors))]
public IActionResult GetStudent(string parametr)
{
    try
    {
        // Database call 1
        // Database call 2
        return Ok(new Student());
    }
    catch (Exception ex)
    {
        Errors errors = new Errors();
        errors.ErrorMessages.Add(ex.Message);
        
        return BadRequest(errors);
    }
}

注意BadRequest只是一个返回的例子,你应该总是返回正确的Http状态码消息,比如404表示未找到,401表示禁止等等

【讨论】:

  • 感谢您的回复。这实际上帮助了我很多。不过,我更改了方法返回类型,而不是 IHttpActionResult 我使用 HttpResponseMessage 来更好地处理一些我需要添加的响应选项。
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 2017-09-07
  • 2018-06-11
  • 2015-05-11
  • 2013-12-13
  • 1970-01-01
  • 2010-10-24
  • 2017-02-24
相关资源
最近更新 更多