I want to show a page when users try to access something that they shouldn't. This restriction is check in custom middleware. When the middleware returns a false and the new controller gets called I don't want the client side url to change.
This is my middleware check:
public async Task Invoke(HttpContext context, IAutorisationService service)
{
var user = service.CreateUserModel(context);
var page = service.CreatePageModel(context);
context.Items.Add("CurrentUser", user);
if (service.UserAllowedToPage(user, page))
await _next.Invoke(context);
else
{
context.Response.Redirect("/Error/CustomError");
}
}
This is the error controller:
public IActionResult CustomError()
{
if (!HttpContext.Items.TryGetValue("CurrentUser", out var o) || !(o is UserModel userModel))
{
return View();
}
if (userModel.IsSuperUser)
{
return View();
}
The views returned here all work fine.
This is my startup.cs (where I'm struggling now):
app.UseMvc(routes =>
{
//routes.MapRoute(
//name: "ErrorRoute",
//template: "{controller=Error}",
//defaults: new {controller = "Error", action = "CustomError"});
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I just can't seem to get it right with any of the combinations I find on the web.
Update
Ok so I'm not getting any further with the policies.
I'll try to explain my situation a bit better:
I have a custom middleware at the end of the pipeline (just before app.UseMvc)
That middleware has a async Task Invoke method that calls a boolean operator in a different class.
Now if the boolean returns true the middleware task does: await _next.Invoke(HttpContext) and I want the middleware to excecute an exception if that boolean returns false.
And when the exception is thrown I want the: app.UseExceptionHandler("/Error/CustomError"); or the app.UseStatusCodePagesWithReExecute("/Error/CustomError");
to catch it and activate the CustomError action in the ErrorController to then return a custom view. Is this even possible? (Sorry if my first question wasn't complete)