我有一個 .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,有沒有一種方法或如何正確地構建它,以便我可以像我的示例中那樣獲得正確的路徑。
uj5u.com熱心網友回復:
閱讀LinkGenerator Class。
定義一個基于端點路由生成絕對和相關 URI 的協定。
您可以在過濾器中解決該問題并使用當前請求的生成鏈接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 }
);
//...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/457083.html
