Home > Mobile >  How to return not found in Program.cs ASP.Net core 6
How to return not found in Program.cs ASP.Net core 6

Time:03-22

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 ();
});

CodePudding user response:

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

return;

CodePudding user response:

There's also a better way I realized that doesn't needs using Microsoft.Net:

context.Response.StatusCode = 404;
return;
  • Related