但是每个方法都这样加会不会觉得很烦?有没有想过只写一次就可以了 上代码:
try
{
var range = Enumerable.Range(1, 3).ToArray();
var result = range[4];
return View();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
我们在方法中先以特性来使用,加上这句代码:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ExceptionFilter.Filter
{
public class CustomerExceptionFilter : Attribute, IExceptionFilter
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
public CustomerExceptionFilter(IHostingEnvironment hostingEnvironment,
IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
}
/// <summary>
/// 发生异常进入
/// </summary>
/// <param name="context"></param>
public async void OnException(ExceptionContext context)
{
if (!context.ExceptionHandled)//如果异常没有处理
{
if (_hostingEnvironment.IsDevelopment())//如果是开发环境
{
var result = new ViewResult { ViewName = "../Handle/Index" };
result.ViewData = new ViewDataDictionary(_modelMetadataProvider,
context.ModelState);
result.ViewData.Add("Exception", context.Exception);//传递数据
context.Result = result;
}
else
{
context.Result = new JsonResult(new
{
Result = false,
Code = 500,
Message = context.Exception.Message
});
}
context.ExceptionHandled = true;//异常已处理
}
}
}
}
<font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);">[TypeFilter(</font><font style="color:rgb(0, 0, 255);background-color:rgb(242, 244, 245);">typeof</font><font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);">(CustomerExceptionFilter))]</font>
<font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);"> <p>Message:@ViewData[</font><font style="color:rgb(128, 0, 0);background-color:rgb(242, 244, 245);">"Exception"</font><font style="color:rgb(0, 0, 0);background-color:rgb(242, 244, 245);">]</p></font>
services.AddControllersWithViews(option =>
{
option.Filters.Add<CustomerExceptionFilter>();
});
//3.0以下的版本好像应该这样写:services.AddMvc();
关于AddMvc/AddMvcCore/AddControllers等区别,移步:https://www.yuque.com/schafferyy/net/twgia8