在我的應用程式中,我想在任何方法拋出 RedirectException 時使用 Redirect。例如... 注意:ActivePeriodException 繼承自 RedirectException
if (Period.ActivePeriod(Db))
throw new ActivePeriodException();
我的 ActivePeriodException 類是
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 :)";
}
這個例子讓我感到震驚:
找不到與 ActionContext 關聯的 IRouter。如果您的應用程式正在使用端點路由,那么您可以獲得一個帶有依賴注入的 IUrlHelperFactory 并使用它來創建一個 UrlHelper,或者使用 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);
}
}
我該如何解決這個問題?
uj5u.com熱心網友回復:
嘗試UrlHelper使用IUrlHelperFactory從背景關系服務中決議的構建:
public void OnException(ExceptionContext context)
{
// ...
var urlHelperFactory = context.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>();
var urlHelper = urlHelperFactory.GetUrlHelper(context);
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414963.html
標籤:
上一篇:物體框架連接表c#
