12 c# asp.net-core-mvc asp.net-core .net-core-2.0
我正在将 .Net 4.6.2 项目迁移到 Net Core 2。
相当于什么HandleErrorAttribute?第 2 行以下接收错误
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomerAuthorize());
filters.Add(new HandleErrorAttribute());
}
Run Code Online (Sandbox Code Playgroud)
错误:
The type or namespace name 'HandleErrorAttribute' could not be found (are you missing a using directive or an assembly reference?
Run Code Online (Sandbox Code Playgroud)
在asp.net core中,您可以使用异常过滤器。
我们可以创建一个自定义异常过滤器,例如:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
....
....
public class HandleExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var result = new ViewResult { ViewName = "Error" };
var modelMetadata = new EmptyModelMetadataProvider();
result.ViewData = new ViewDataDictionary(
modelMetadata, context.ModelState);
result.ViewData.Add("HandleException",
context.Exception);
context.Result = result;
context.ExceptionHandled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
可以将过滤器添加到管道的三个范围之一。您可以使用属性将过滤器添加到特定操作方法或控制器类。或者您可以为所有控制器和操作全局注册一个过滤器。通过将过滤器添加到ConfigureServices中的MvcOptions.Filters集合中来全局添加过滤器:
services.AddMvc(options=>options.Filters.Add(new HandleExceptionAttribute()));
Run Code Online (Sandbox Code Playgroud)
请参阅在 ASP.NET Core 中创建自定义异常过滤器。
| 归档时间: |
|
| 查看次数: |
7517 次 |
| 最近记录: |