如何在ASP.NET Core中構造UrlHelper,及ASP.NET Core MVC路由講解


參考文章:

Unable to utilize UrlHelper

 

除了上面參考文章中介紹的方法,其實在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路由講解

在 ASP.NET Core 中路由到控制器操作

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM