Exception filters

Hung Angu 1 Reputation point
2020-12-25T02:36:08.897+00:00

Dear Sir/Mam,

My name is Vuong Sy Hung from Vietnam (vuongsyhung@Microsoft Corporation .com; +84979382919)
I am writing this letter to request information about Creating Exception filters.
When I was reading the Exception filters (https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0#exception-filters). I started to try to follow your instructions, step by step.

Here is Controller:

using AdvancedFilter.CustomFilters;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AdvancedFilter.Controllers
{
[TypeFilter(typeof(CustomExceptionFilter))]
public class FailingController : Controller
{
public IActionResult Index()
{
throw new Exception("Testing custom exception filter.");
}
}
}

here is Exception filter:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Hosting;

namespace AdvancedFilter.CustomFilters
{
public class CustomExceptionFilter : IExceptionFilter
{
private readonly IWebHostEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;

    public CustomExceptionFilter(  
        IWebHostEnvironment hostingEnvironment,  
        IModelMetadataProvider modelMetadataProvider)  
    {  
        _hostingEnvironment = hostingEnvironment;  
        _modelMetadataProvider = modelMetadataProvider;  
    }  

    public void OnException(ExceptionContext context)  
    {  
        if (!_hostingEnvironment.IsDevelopment())  
        {  
            return;  
        }  
        var result = new ViewResult { ViewName = "CustomError" };  
        result.ViewData = new ViewDataDictionary(_modelMetadataProvider,  
                                                    context.ModelState);  
        result.ViewData.Add("Exception", context.Exception);  
         
        context.Result = result;  
    }  
}  

}

the view:

@{
Layout = null;
var exception = ViewData["Exception"] as Exception;
}

<!DOCTYPE html>

<html>
<head>
<title>Custom Error Page</title>
</head>
<body>
<div>
<h1>Custom Error Page</h1>
</div>
<footer>
Exception Details: @Exception Chen .Message
</footer>
</body>
</html>

And here is startup file:

using AdvancedFilter.CustomFilters;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AdvancedFilter
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }  

    
    public void ConfigureServices(IServiceCollection services)  
    {  
        services.AddControllersWithViews();  
    }  

   
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
    {  
        if (env.IsDevelopment())  
        {  
            app.UseDeveloperExceptionPage();  
        }  
        else  
        {  
            app.UseExceptionHandler("/Home/Error");  
            
            app.UseHsts();  
        }  
        app.UseHttpsRedirection();  
        app.UseStaticFiles();  

        app.UseRouting();  

        app.UseAuthorization();  

        app.UseEndpoints(endpoints =>  
        {  
            endpoints.MapControllerRoute(  
                name: "default",  
                pattern: "{controller=Home}/{action=Index}/{id?}");  
        });  
    }  
}  

}

All things are the same yours

But when I run it, the filter I created doesn't seem to work (As shown in the pic01). I don't know where I went wrong.
I look forward to receiving your instructions.
Thank you very much.
Yours faithfully.
Vuong Sy Hung
51108-pic01.png

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Brando Zhang-MSFT 2,956 Reputation points Microsoft Vendor
    2020-12-25T06:14:43.08+00:00

    @Hung Angu , according to your description and codes, I have created a test demo on my side, it works well. There is no error for your codes.

    After I research your image, I found the page you have uploaded is still loading. I suggest you could try to click continue button to see if the exception filter is working well or not.

    More details, you could refer to below image:

    51221-845.gif

    0 comments No comments