我有一个ASP.NET Core 1.0 Web API应用程序,并试图弄清楚如果我的控制器正在调用的函数出错,如何将异常消息传递给客户端.

我试了那么多东西,但没有一样能做到IActionResult.

我不明白为什么这不是人们需要的普通东西.如果真的没有解决办法,谁能告诉我为什么?

我确实看到一些使用HttpResponseException(HttpResponseMessage)的文档,但为了使用它,我必须安装compat垫片.在Core1.0中有没有一种新的方法来做这些事情?

以下是我一直在try 的垫片,但它不起作用:

// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
{
    Customer c = _customersService.GetCustomerById(id);
    if (c == null)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent("Customer doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
            StatusCode = HttpStatusCode.NotFound

        };

        throw new HttpResponseException(response);

        //return NotFound();
    }
    return new ObjectResult(c);
}

当抛出HttpResponseException时,我查看客户端,在内容中找不到我正在发送的消息.

推荐答案

下面是一个简单的错误DTO类

public class ErrorDto
{
    public int Code {get;set;}
    public string Message { get; set; }

    // other fields

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

然后使用ExceptionHandler个中间件:

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
                    context.Response.ContentType = "application/json";

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        var ex = error.Error;

                        await context.Response.WriteAsync(new ErrorDto()
                        {
                            Code = <your custom code based on Exception Type>,
                            Message = ex.Message // or your custom message
                            // other custom data
                        }.ToString(), Encoding.UTF8);
                    }
                });
            });

Asp.net相关问答推荐

HttpRuntime.Cache[] 与 Application[]

如何在asp.net中单击按钮的新选项卡中打开页面?

判断 asp.net mvc 4 应用程序中的 ssl 协议、密码和其他属性

Automapper - 映射器已初始化错误

如何在没有实体框架的情况下使用 ASP.NET Identity 3.0

在 RedirectToAction 调用中传播 QueryString 参数

如何将 global.asax 文件添加到 ASP.NET MVC4 项目?

为什么我不能在 ASP.net MVC 中使用服务器控件?

UseSqlServer 方法缺少 MVC 6

您如何以编程方式填写表格并发布网页?

IIS 10 上的 ASP.NET Core 404 错误

MVC5 身份验证中的......与主域之间的信任关系失败

无法共同创建探查器错误 - 但未使用探查器

带有 ASP.NET WebMethod 的 Jquery AJAX 返回整个页面

根据 DropDownList 的值动态启用或禁用RequiredFieldValidator

HttpContext.Current 在 MVC 4 项目中未解决

Docker 中的 ASPNETCORE_ENVIRONMENT

StyleBundle 索引超出了数组的范围

Application_Start 和 Application_OnStart 之间的区别

如何在不遍历每个循环的情况下从字典对象中获取所有键(仅键)