I'm using .Net Core MVC 3.0 which defaults to Endpoint Routing
The default route config is:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Link}/{action=Index}/{id?}"
});
That will allow me to do CRUD operations on my "Links"
e.g. /Link/Edit/123
What I need to be able to do is catch and route any request which is NOT a CRUD operation to another controller and action
e.g. /blahblah
So that I can process them as I like (probably a redirect, maybe just a friendly notice, could be anything!)
Back in my .Net Framework MVC, one would add a route config like this:
routes.MapRoute(
name: "MyCatchAll",
url: "{key}",
defaults: new { controller = "MyController", action = "MyAction" },
constraints: new { key = new MyConstraint() }
);
(the purpose of the constraint is simply an optional check that I might need to use for example, to ensure that blahblah matches an expected value)
However, I cannot get this to work in .Net Core MVC 3.0
Any pointers would be most appreciated.
For asp.net core 3.0, you could use below configuration:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyCatchAll",
pattern: "{key}",
defaults: new { controller = "MyController", action = "MyAction" },
constraints: new { key = new MyConstraint() }
);
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
MyConstraint.cs
public class MyConstraint: IRouteConstraint
{
public bool Match(HttpContext httpContext,
IRouter router,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
var url = values["key"];
//your logic to check
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With