[SOLVED] How to return not found in Program.cs ASP.Net core 6


I’ve tried to improve my site’s security, & one of things I’ve tried is when a user is not admin & wants to access admin page, system returns NotFound. This makes impossible to a hacker to know your admin page. But how to do it?
This is what I’ve tried to. I’ve made a Middleware in program.cs to check for URL & redirect somewhere, which isn’t what I want. Even I’ve tried to set the status code to 404, but that doesn’t works. what I want to access here, is return NotFound (); Method. Is there a way to do it. Thanks

app.Use (async (context, next) =>
    if (context.Request.Path.StartsWithSegments ("/Admin"))
        if (/* Checking if user is not admin */)
            // context.Response.Redirect ("/");
            // The code to do same as return NotFound ();
    await next.Invoke ();


// Write response
context.Response.StatusCode = ((int)HttpStatusCode.NotFound);


Answered By – matt sharp

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *