I'm having one of those "I can't believe it's this difficult moments". In .NET Framework I used to sometimes create custom Authorization filters and, if I needed to, I could redirect the user using
context.Result = new RedirectToActionResult("ChooseAuthenticationMethod", "Account");
Now I'm using the latest versions of .NET more (specifically, in this case, .NET 7), I'm trying to get to grips with the Authorization Middleware, which seems like the preferred way to go for a lot of what I would have previously used a custom Authorize attribute for.
I have this code, which works perfectly:
public class TestAuthorizationMiddleware : IAuthorizationMiddlewareResultHandler
{
private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();
public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
{
if (authorizeResult.Challenged && policy.AuthenticationSchemes.Count == 0)
{
context.Response.Redirect("Account/ChooseAuthenticationMethod");
}
else
{
await defaultHandler.HandleAsync(next, context, policy, authorizeResult);
}
}
}
However, I'm trying to figure out how to replace the hard-coded, relative URL ("Account/ChooseAuthenticationMethod") with an absolute one which ASP.NET generates. If I was inside a controller I could just use Url.Action
, but I'm not. I've been reading through Stack Overflow questions similar to this for the past hour and can't find anything that seems to do the job. Surely, especially with access to HttpContext
and the Request
, this should be easy?