我将从ASP.NET 4.5切换到ASP.NET 5,并使用它生成一些RESTful web服务。在4.5中,我能够在一个动作中抛出一个异常,并让它返回给调用者。我想在ASP.NET 5中这样做,但我还没有运气。我希望避免在每一个动作上使用Try/Catch来完成这个任务。
来自Visual有关窗口的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:
我更改了我的示例以反映这一点,但在遇到意外异常时,我希望将异常信息返回给调用者,而不是我自己抛出的异常。代码就是一个例子,我知道特定情况可以通过null ref检查来解决。
编辑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();
}发布于 2016-02-11 19:43:05
我希望避免在每一个动作上使用Try/Catch来完成这个任务。
https://docs.asp.net/en/latest/fundamentals/middleware.html
请注意,中间件还意味着不需要添加任何ExceptionFilterAttribute的
发布于 2016-02-11 19:39:10
您可以通过使用ExceptionFilterAttribute来实现这一点。要捕获的每种类型的异常都需要一个。然后您需要在FilterConfig.cs中注册它
public class RootExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is Exception)
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
// or...
// context.Response.Content = new StringContent("...");
// context.Response.ReasonPhrase = "random";
}
}
}https://stackoverflow.com/questions/35348466
复制相似问题