C# ASP.NET WebApi在异常时返回不同的对象

C# ASP.NET WebApi在异常时返回不同的对象,c#,asp.net-mvc,asp.net-web-api,C#,Asp.net Mvc,Asp.net Web Api,我目前正在开发一个API,需要为API返回一些对象,或者在某个地方出现故障时返回一个错误,这主要是因为我依赖于数据库调用 以下是我的一些代码: public Student GetStudent(string parametr) { try { // Database call 1 // Database call 2 return new Student();

我目前正在开发一个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,它完全符合我关于编码部分的需要,但这不适用于swagger。我的web应用程序不是asp.net核心

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


提前感谢,

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

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

public class Errors
{
    public List<string> ErrorMessages { get; set; } = new List<string>();
}
对于.NET核心

[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禁止等等

根据异常情况,您应该返回适当的Http状态(如400或409或500)以及一个一般性错误,具体取决于错误的原因/来源。至于如何在api中实现这一点,我会搜索“Swagger如何返回http状态码”,您能否详细说明一下,HttpResponse在Swagger中不适用于您,因为它不是ASP.NET核心应用程序?它应该会起作用。在你的情况下,什么特别不起作用?谢谢你的回答。这实际上对我帮助很大。不过,我更改了方法返回类型,而不是使用HttpPactionResult来更好地处理需要添加的一些响应选项。
[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);
    }
}