Search code examples
asp.net-core-2.1aspnetboilerplate

Custom HTTP response in ASP.NET Core 2.x Boilerplate


I'm trying to throw my own custom exceptions from within an AppService. Included with the exception being thrown, I would like to add my own HTTP status. Regardless of the various methods specified on Stackoverflow as well as other sources, I'm unable to override the default functionality of ASP.NET Boilerplate. Some assistance would be greatly appreciated.

Many thanks!


Solution

  • You can subclass AbpExceptionFilter (or implement your own IExceptionFilter) and then add it:

    Step 1

    services.AddMvc(options =>
    {
        options.Filters.AddService(typeof(MyExceptionFilter), order: 1);
    });
    

    Step 2 Add the following code in the XYZWebHostModule class:

            public override void PreInitialize()
            {
                Configuration.ReplaceService(typeof(IExceptionFilter),
                    () =>
                    {
                        IocManager.Register<IExceptionFilter, MyExceptionFilter>(DependencyLifeStyle.Transient);
                    });
            }
    

    Step 3 Subclass AbpExceptionFilter and override GetStatusCode as well as HandleAndWrapException, based on your requirements and implementations

    References