这是我在Startup.cs中的Startup()方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
loggerFactory.AddNLog();
}
app.UseApplicationInsightsRequestTelemetry(); // Needs to be first
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
await context.Response.WriteAsync(new ErrorResponse
{
Code = 500,
Message = ex.Message
}.ToString(), Encoding.UTF8);
}
});
});
app.UseApplicationInsightsExceptionTelemetry(); // After error page
app.UseMvc();
}
这是我在控制器中的路线。
[HttpGet]
[Route("Test")]
public string Test()
{
if(!string.IsNullOrEmpty(Request.Query["test"]))
throw new Exception("Testing..");
return "Hello.";
}
ErrorResponse.cs
public class ErrorResponse
{
public int Code { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
当我转到http://website/test时,它会显示“你好”。但是当我转到http://website/test?test=asd时,它会抛出我的异常(路径中的异常),而不是使用UseExceptionHandler捕获它并停止程序。
我的目标是让它显示以下json:
{
"Error": 500,
"Message": "Testing..."
}
我正在使用asp.net核心。
答案 0 :(得分:0)
您的应用程序因异常而停止,因为您在VS中以调试模式运行它并附加了调试程序。例如,从控制台运行应用程序(或在VS中禁用“中断异常”选项。
答案 1 :(得分:0)
旧帖子,但我遇到了同样的问题。
可能有一些全局应用的异常过滤器。在Startup.ConfigureServices
中查找MVC配置。我遇到了services.AddMvcOptions(o => o.Filters.Add<ErrorHandlerAttribute>())
,这就是问题所在。