C
C#nox7

ASP Core 8 - Custom 404 Handling

I have a few scenarios where I need to show a different kind of view and a bit of different logic depending on what type of authenticated user in my app experiences a "404" However, I don't understand how to capture the 404. I am using attribute routes and have the following middleware.
public class NotFoundMiddleware
{
private readonly RequestDelegate RequestDelegate;

public NotFoundMiddleware(RequestDelegate RequestDelegate)
{
this.RequestDelegate = RequestDelegate;
}

public async Task InvokeAsync(HttpContext context)
{
if (context.Response.StatusCode == StatusCodes.Status404NotFound)
{
context.Request.Path = "/client/errors/404";
}

await RequestDelegate(context);
}
}
public class NotFoundMiddleware
{
private readonly RequestDelegate RequestDelegate;

public NotFoundMiddleware(RequestDelegate RequestDelegate)
{
this.RequestDelegate = RequestDelegate;
}

public async Task InvokeAsync(HttpContext context)
{
if (context.Response.StatusCode == StatusCodes.Status404NotFound)
{
context.Request.Path = "/client/errors/404";
}

await RequestDelegate(context);
}
}
Setting a breakpoint with the debugger shows that providing a gibberish URL still is giving a status code of 200 - so my middleware doesn't handle it. How do I capture the a situation where there is no matching route or static file? I am trying to run code only when no route or static file was matched.
No description
N
nox717d ago
Upon further investigation, it looks like HttpContext has an Endpoint property that is null if no matching route occurred. If I put my middleware at the end of a chain, unless anyone else has any further information - it seems this is how to tell if the request has no matching route and I can use this to assume it will 404.
No description
UU
Unknown User17d ago
N
nox717d ago
Yeah, I've read through that - unfortunately it doesn't do what I need here. It forces me to use their internal error handling. Or in the case of a custom IExceptionHandler - only when an exception is thrown. I need it to go to custom paths based on specific HttpContext data.
UU
Unknown User17d ago
N
nox717d ago
UseStatusCodePagesWithReExecute is almost there, but it doesn't give me much controller in directing it to completely different routes Ah, we thought the same thing
UU
Unknown User17d ago
N
nox717d ago
I guess I could use it and just handle the logic I need within the Controller I redirect to (showing different views). So I'll go down that path
UU
Unknown User17d ago
N
nox717d ago
MVC/Razor
UU
Unknown User17d ago
N
nox717d ago
E.g., I am trying to show 3 different 404 views. One for authenticated clients, one for authenticated staff, and one for non-authenticated users
UU
Unknown User17d ago
N
nox717d ago
There are other situations I need the 404 page to be shown. E.g., when an object is missing from a request Url that has an Id in the parameter. So I wanted to have it all (all 404 scenarios) propagate up to the top and then the top handles it based on the currently authenticated user
N
nox717d ago
app.UseStatusCodePagesWithReExecute("/errors/{0}");
app.UseStatusCodePagesWithReExecute("/errors/{0}");
No description
N
nox717d ago
This works well and as I need it to, so thanks.
UU
Unknown User17d ago
N
nox717d ago
Ah, I see what you mean. That's not a bad idea either.
UU
Unknown User17d ago
N
nox717d ago
I don't use the normal identity system, but I get what you're saying.
UU
Unknown User17d ago
N
nox717d ago
I don't use that system in my app
UU
Unknown User17d ago
N
nox717d ago
Because two users can be logged in at one time I use a custom user system
UU
Unknown User17d ago
Want results from more Discord servers?
Add your server
More Posts
Add suffix to version without it showing up as a prereleaseI'm writing a lib that wraps a bunch of external GRPC APIs and exposes them via the same interface. Help refactor serviceHi! I have data of many `Station` models. Their information updates every ~60 minutes. I need to sto✅ looking for help/contributorsDotmenu is a straightforward console menu library designed to streamline user interactions in consolHow to find relative file path for file inside of project?Dealing with a C# console application, I have a folder inside the project named Files and inside thaPassing parameters to overloaded constructorHow would I pass the texture2D variable to be handled in the second constructor. Obviously return doI am trying to store data in database using EF my code run fine but its not storing dataif (response.IsSuccessStatusCode) { var json = await resUsing ref for large data types.Hi, just looking for a little clarification on the *ref* keyword when passing data into a function. crud operations with blazor serverI have a backend that I built and now I want to use it with api calls. I created same model with bacminor glitch, player twitchingso i have a glitch where the player starts "twitching" when you walk beside a block or just on a blo✅ BackgroundWorker getting progressI have a winform applications and with this I have put a ProgressBar on it. I was manually changing My tech stack, what to focus now?- .NET Core - Entity Framework Core (Code First) - MVC - Web API - Identity and JWT - Mediator & CQRBuild Issue due to $(Platform) valueWe are facing build issue when we try to build .net project in custom project configuration, like DePFX certificate for signing the application packageI am trying to use a certificate from azure key vault, but it says that it is invalid or another reaInheritance best practice: test Type of subclass or use enum?See attched UML. Just wondering what the best practice is? Is it better to test the Type of BaseEffeC# - Oracle DataBase Converting the Date (Oracle) to a c# DateTime PropertyHow can I replace TO_TIMESTAMP in my select query with the format my c# code uses? I have a class wiAdding Multitenancy through Finbuckel in the single tenant Dotnet applicationHey I was just implementing the Multitenancy to my existing single tenant dotnet application where oI need help with Deployment LogicSo let's say I have 10 servers (already setup with a load balancer and all that stuff) which all runFilesystem packer slows down after 30k filesAfter the filesystem packer has hashed all 255k files then the DB operations starts to slow down thewhy is my player floating, twitching and can almost not go up a rampso im learning c# for unity and i made a (very) litle scene to test my first person controls i made.Model, Dto, Entity - Id?Hi, I'm messing with a simple CRUD application. My PatientEntity looks like this: public cla