当前位置:首页 > Windows程序 > 正文

但是在处理错误时

2024-03-31 Windows程序

在.NET Core中MVC和WebAPI已经组合在一起,,都担任了Controller,但是在措置惩罚惩罚错误时,就很不一样,MVC返回错误页面给浏览器,WebAPI返回Json或XML,而不是HTML。UseExceptionHandler中间件可以措置惩罚惩罚全局异常

app.UseExceptionHandler(options => { options.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { //TODO 定制响应布局的一致性 string text = JsonConvert.SerializeObject(new { message = ex.Error.Message }); await context.Response.WriteAsync(text); } }); });

打开ValuesController.cs,改削代码,手动抛出一个异常

[HttpGet] public IEnumerable<string> Get() { int a= 1; int b = a / 0; return new string[] { "value1", "value2" }; }

运行应用措施你应该可以看到


技术分享图片

另一种方法是使用IExceptionFilter

public class CustomExceptionFilter : Microsoft.AspNetCore.Mvc.Filters.IExceptionFilter { public void OnException(ExceptionContext context) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.HttpContext.Response.ContentType = "application/json"; var ex = context.Exception; if (ex != null) { //TODO 定制响应布局的一致性 string text = JsonConvert.SerializeObject(new { message = ex.Message }); context.HttpContext.Response.WriteAsync(text); } } }

最后在Startup.cs ConfigureServices要领中添加我们的过滤器

public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(typeof(CustomExceptionFilter)); }); }

在这篇文章中我们使用了内置的中间件和内置的异常过滤器措置惩罚惩罚异常。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/35383.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494590访问次数
  • 建站天数
  • 友情链接