Sunday, 4 October 2020

                show custom exception page in .net core


Step 1  first create the solution as below  and 





Step 2   
then create the error controller 


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

namespace GlobalException.Controllers
{
    public class ErrorController : Controller
    {
        [Route("Error/{StatusCode}")]
        public IActionResult StatusCodeHandle(int statusCode)
        {
            switch (statusCode)
            {
                case 404:
                    ViewBag.ErrorMessasge = $"I am having {statusCode}" + " Error code Message";
                    break;
            }
            return View(statusCode);
        }

    }
}

Step 3 create the view as below,StatusCodeHandle.cshtml

<h1>@ViewBag.ErrorMessasge</h1>
eror


Step 4 Now write the code in start file to call custom page,below highlighted code is mandatory to route the request

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GlobalException.WebApi.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews(); // This is the imporatant line for handling No service reg
            services.AddMvcCore();

            services.AddScoped<IExceptionLogService, ExceptionLogService>();
            services.AddScoped<DbExceptionFiltercs>();// for Error Log
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithRedirects("/Error/{0}");       this is the import line 
            }
            

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}


now ,i am doing the request of http://localhost:51605/weatherforecast/tip,result will be like below





No comments:

Post a Comment