• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 

posted @ 2019-01-04 00:28  PowerCoder  阅读(1849)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3