Asons
Asons

Reputation: 87262

Catch url with no route

To catch an url which doesn't have a route one can do something like this

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/Error/Nopage", "{*url}");
    });

But then I noticed that the OnGet() method in Nopage.cshtml.cs gets called for all routes, even the one's that has a route.

Is this the standard behavior, and how one is suppose to catch non-routed url's? ...or is there some other way to catch url with no routes.

Also, from a workload/performance perspective, it feels kind of wrong to initiate and load a page model that will not be used.


As a note, prior to using AddPageRoute I did like this in Startup.cs, which worked just fine, though the above felt more as how one is suppose to do it.

app.UseMvc();

// Page missing in MVC...
app.Use(async (context, next) =>
{
    //simplified code snippet
    s = await File.ReadAllTextAsync(Path.Combine(env.WebRootPath, "pagemissing.html"));
    await context.Response.WriteAsync(s);
});

Upvotes: 1

Views: 147

Answers (1)

Mike Brind
Mike Brind

Reputation: 30110

It seems that you are trying to intercept 404s and return a custom error page. ASP.NET Core includes middeleware that does this: StatusCodePagesMiddleware. You put the following in your Configure method:

app.UseStatusCodePagesWithReExecute("/{0}");

where {0} is a placeholder for the status code. Create a page called 404.cshtml and it will be executed whenever someone browses to a non-existent URL. You can also create a page named 500.cshtml and it will be executed if there is a server error.

See more about this here: https://www.learnrazorpages.com/configuration/custom-errors

Upvotes: 1

Related Questions