我有一个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相关问答推荐

无法翻译 LINQ

IIS 中 ASP.net 应用程序的单独应用程序池

ASP.NET:获取自 1970 年 1 月 1 日以来的毫秒数

ASP.NET GridView 第二个标题行跨越主标题行

IIS 将旧用户名返回到我的应用程序

Webapi、Webhost和Owin的关系

学习什么 - Ruby on Rails 或 ASP .NET MVC...鉴于熟悉 ASP .NET

哪些行为驱动开发 (BDD) 工具/框架可用于 Microsoft Stack?

ASP.NET MVC4 异步控制器 - 为什么要使用?

带有完整内存错误的 WCF 服务(内存门判断失败,因为可用内存) - 如何解决

在 ASP.NET 中使用 Messenger Connect 客户端库时出现 Javascript 错误

您使用哪个 .NET Memcached 客户端,EnyimMemcached 与 BeITMemcached?

<%# Eval("State") %> 或 <%# DataBinder.Eval(Container.DataItem, "state")%>

GMT 和 UTC 一样吗?

要调用此方法,Membership.Provider属性必须是ExtendedMembershipProvider的实例

MSBuild DeployOnBuild=true 不发布

将字典绑定到中继器

如何检索 X509Store 中的所有证书

如何创建代表 colored颜色 的随机十六进制字符串?

在没有等待 #2 的情况下调用异步方法