ASP.NET Core - 异常过滤器属性如何构建 URL like Url.Action
ASP.NET Core - Exception filter attribute how to build URL like Url.Action
我有一个用于处理异常的 .NET Core 属性:
public class ExceptionActionAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
.... some code
// this is how you do it in .NET 4 MVC
var exceptionUrl = Url.Action("Test", "Error", new { errorId = errorUid.ToString() });
}
}
我想像在 .NET 4 中一样使用 Url.Action 来构建 Url,有没有一种方法或者构建它的正确方法,以便我可以获得正确的路径在我的例子中。
Defines a contract to generate absolute and related URIs based on endpoint routing.
您可以在过滤器中解决该问题并使用当前请求的 HttpContext
生成链接
public class ExceptionActionAttribute : ExceptionFilterAttribute {
public override void OnException(ExceptionContext context) {
// .... some code
// resolve LinkGenerater
LinkGenerater linkGenerater = context.HttpContext.RequestServices.GetService<LinkGenerater>()
// and use it to generate URLs
var exceptionUrl = linkGenerater.GetUriByAction(context.HttpContext,
action: "Test",
controller: "Error",
values: new { FileId = 1 }
);
//...
}
}
我有一个用于处理异常的 .NET Core 属性:
public class ExceptionActionAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
.... some code
// this is how you do it in .NET 4 MVC
var exceptionUrl = Url.Action("Test", "Error", new { errorId = errorUid.ToString() });
}
}
我想像在 .NET 4 中一样使用 Url.Action 来构建 Url,有没有一种方法或者构建它的正确方法,以便我可以获得正确的路径在我的例子中。
Defines a contract to generate absolute and related URIs based on endpoint routing.
您可以在过滤器中解决该问题并使用当前请求的 HttpContext
public class ExceptionActionAttribute : ExceptionFilterAttribute {
public override void OnException(ExceptionContext context) {
// .... some code
// resolve LinkGenerater
LinkGenerater linkGenerater = context.HttpContext.RequestServices.GetService<LinkGenerater>()
// and use it to generate URLs
var exceptionUrl = linkGenerater.GetUriByAction(context.HttpContext,
action: "Test",
controller: "Error",
values: new { FileId = 1 }
);
//...
}
}