我有一个ASP.NET Core 1.0 Web API应用程序,并尝试弄清楚如果我的控制器调用的函数错误输出异常消息到客户端.
我尝试了很多东西,但没有实现IActionResult.
我不明白为什么这不是人们需要的常见事情.如果真的没有解决方案可以有人告诉我为什么?
我确实看到了一些使用的文档HttpResponseException(HttpResponseMessage),但为了使用它,我必须安装compat shim.在Core 1.0中有没有新的方法来做这些事情?
这是我一直在尝试使用垫片,但它不起作用:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
当HttpResponseException抛出时,我查看客户端,无法找到我在内容中发送任何内容的消息.
我有一个 .NET Framework 4.8 / AngularJS 应用程序,我正在尝试升级到 .NET 6,以便我可以开始尝试更新的前端框架(如 Blazor)。升级进展顺利,但当从 Angular JS 代码调用我的 API 方法之一时,我总是看到此错误:
System.NotSupportedException: Serialization and deserialization of 'System.IntPtr' instances are not supported. Path: $.TargetSite.MethodHandle.Value.
---> System.NotSupportedException: Serialization and deserialization of 'System.IntPtr' instances are not supported.
at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at …Run Code Online (Sandbox Code Playgroud) 我想将异常消息返回给AngularJS UI.作为后端,我使用ASP.NET Core Web Api控制器:
[Route("api/cars/{carNumber}")]
public string Get(string carNumber)
{
var jsonHttpResponse = _carInfoProvider.GetAllCarsByNumber(carNumber);
if (jsonHttpResponse.HasError)
{
var message = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(jsonHttpResponse.ErrorMessage)
};
throw new HttpResponseException(message);
}
return jsonHttpResponse.Content;
}
Run Code Online (Sandbox Code Playgroud)
但在Angular方面,失败承诺只能看到状态和statusText"内部服务器错误":
如何将错误消息传递给Core Web Api的Angular $ http失败承诺?