參考文章:
除了上面參考文章中介紹的方法,其實在ASP.NET Core MVC的Filter攔截器中要使用UrlHelper非常簡單。如下代碼就展示了如何在IActionFilter攔截器中構造和使用UrlHelper,其它MVC的Filter攔截器如法炮制即可:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Routing; using System; namespace WebApi.Filters { public class MyActionFilterAttribute : Attribute, IActionFilter { /// <summary> /// OnActionExecuting方法在Controller的Action執行前執行 /// </summary> public void OnActionExecuting(ActionExecutingContext context) { IUrlHelper urlHelper = new UrlHelper(new ActionContext(context.HttpContext, context.RouteData, context.ActionDescriptor)); string actionUrl = urlHelper.Action("Display", "User", new { id = 15 }); } /// <summary> /// OnActionExecuted方法在Controller的Action執行后執行 /// </summary> public void OnActionExecuted(ActionExecutedContext context) { IUrlHelper urlHelper = new UrlHelper(new ActionContext(context.HttpContext, context.RouteData, context.ActionDescriptor)); string actionUrl = urlHelper.Action("About", "Home", new { id = 15 }); } } }
OnActionExecuting方法運行效果如下:
OnActionExecuted方法運行效果如下:
ASP.NET Core MVC路由講解