我正在从 ASP.NET 4.5 切换到 ASP.NET 5 并使用它来生成一些 RESTful Web 服务。在 4.5 中,我能够在操作中抛出异常并将其返回给调用者。我想在 ASP.NET 5 中这样做,但我还没有成功。我想避免在每个操作上都使用 Try/Catch 来完成此操作。
来自 Visual Studio 的有关窗口的 ASP.NET 信息:ASP.NET 和 Web 工具 2015(RC1 更新 1)14.1.11120.0
这是我用来测试它的代码示例。
[Route("[controller]")]
public class SandController : Controller
{
/// <summary>
/// Test GET on the webservice.
/// </summary>
/// <returns>A success message with a timestamp.</returns>
[HttpGet]
public JsonResult Get()
{
object TwiddleDee = null;
string TwiddleDum = TwiddleDee.ToString();
return Json($"Webservice successfully called on {DateTime.Now}.");
}
}
我能够调用此操作并看到我的断点命中,但在调用端我收到 500 错误代码并且响应中没有正文。
编辑 1:
我改变了我的例子来反射(reflect)这一点,但我想在我遇到意外异常的情况下将异常信息返回给调用者,而不是我自己抛出的异常。该代码是一个示例,我知道可以通过空引用检查来解决特定情况。
编辑 2:
@danludwig 指出了生成此解决方案的中间件的 MSDN 文档:
private void ConfigureApp(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
// Adding middleware to catch exceptions and handle them
app.Use(async (context, next) =>
{
try
{
await next.Invoke();
}
catch (Exception ex)
{
context.Response.WriteAsync($"FOUND AN EXCEPTION!: {ex.Message}");
}
});
app.UseMvc();
}
最佳答案
I want to avoid using a Try/Catch on every action to accomplish this.
https://docs.asp.net/en/latest/fundamentals/middleware.html
请注意,中间件还意味着您无需添加任何 ExceptionFilterAttribute
关于c# - ASP.NET 5 API 向调用方返回异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35348466/