Thursday, 3 March 2022

Redirecting Custom error in .Net Core

When we where working on .net mvc or aspx we  where configuring into the web.config file as default error page, like below.

 

<system.web>

    <customErrors mode="On">

      <error statusCode="404" redirect="/PageNotFound?" />

      <error statusCode="302" redirect="/unauthorised" />

    </customErrors>

</system.web>

 

But in .Net core we dont have web.config file to configure default error page.

In this case we need to configure it in startup.cs file.

 

app.Use(async (context, next) =>

            {

                 await next.Invoke();

                 if (context.Response.StatusCode == 302)

                {

                    context.Response.Redirect("error/Error302"true);

                }

 

                if (context.Response.StatusCode == 404)

                {

                    context.Response.Redirect("error/Error404"true);

                }

             });

 

write the  controller with error.

public class ErrorController : Controller

    {

     

        public IActionResult Error302()

        {

            return View();

        }

 

        public IActionResult Error404()

        {

            return View();

        }

    }


No comments:

Post a Comment