如何在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 中路由到控制器操作

 

转载于:https://www.cnblogs.com/OpenCoder/p/10217717.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值