In my app, I want to use Redirect when any method throws a RedirectException.
For example…
Note: ActivePeriodException inherits from RedirectException
if (Period.ActivePeriod(Db))
throw new ActivePeriodException();
My ActivePeriodException class is
public class ActivePeriodException : RedirectException
{
public ActivePeriodException ()
{
PathRedirect = Constantes.PathMantenimiento;
}
protected ActivePeriodException (SerializationInfo serializationInfo, StreamingContext streamingContext) :
base(serializationInfo, streamingContext)
{
PathRedirect = Constantes.PathMantenimiento;
}
public override string Message =>
"Hello World :)";
}
And this example throws me:
Could not find an IRouter associated with the ActionContext.
If your application is using endpoint routing then you can get a IUrlHelperFactory with dependency injection
and use it to create a UrlHelper, or use Microsoft.AspNetCore.Routing.LinkGenerator.
public override void OnException(ExceptionContext context)
{
_logger = ApplicationLogging.LoggerFactory.CreateLogger(context.RouteData.Values["controller"].ToString());
HandleCustomException(context);
base.OnException(context);
}
private void HandleCustomException(ExceptionContext context)
{
if (context.Exception is RedirectException exception)
{
var urlHelper = new UrlHelper(context);
var path = exception.PathRedirect;
path = IsHTTP(path) ? path : urlHelper.RouteUrl(path); //HERE IS THE PROBLEM
_logger.LogInformation(ApplicationLogging.ExceptionMessage(context.Exception));
Session.MsjErrorView = exception.Message;
context.HttpContext.Response.Redirect(path);
FuncionesUtiles.ArmarRespuestaErrorRedirect(context, path);
if (exception.NotificarViaMail)
MailHelper.MandarMail(MailHelper.GetMensajeMailDeError(context), new List<string> { Configuracion.GetValueFromCache(Configuraciones.MailEnvioErrores) }, Constantes.MailSubject);
}
else if (context.Exception is CustomException)
{
_logger.LogInformation(ApplicationLogging.ExceptionMessage(context.Exception));
FuncionesUtiles.ArmarMsgRespuestaError(context, null);
}
}
How can I fix that problem?
>Solution :
Try building UrlHelper with IUrlHelperFactory resolved from the context services:
public void OnException(ExceptionContext context)
{
// ...
var urlHelperFactory = context.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>();
var urlHelper = urlHelperFactory.GetUrlHelper(context);
// ...
}