我在asp.net core 2.1应用程序中有一个自定义异常处理程序
img_inv = 255 - img;
我已经在startup.cs中注册了该中间件
public class ExceptionHandler
{
private readonly RequestDelegate next;
public ExceptionHandler(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var result = JsonConvert.SerializeObject(new HttpClientResponseContract
{
ErrorMessage = exception.Message,
ResponseCode = HttpStatusCode.InternalServerError
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await context.Response.WriteAsync(result);
}
}
如果发生异常,我可以在此类中命中断点,但在响应中未得到结果对象。实际上,除了响应中的500 Internal Server Error外,我什么也没得到。
我在这里做什么错了?
答案 0 :(得分:1)
这是正在运行的演示。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseMiddleware<ExceptionHandler>();
//rest service
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "catalog",
template: "Catalog/{controller}/{action=Index}/{id?}");
});
}