首页 > 编程语言 >Asp.Net Core 之 @Html.Action 迁移

Asp.Net Core 之 @Html.Action 迁移

时间:2023-08-10 23:35:18浏览次数:37  
标签:Core Asp helper action controller Html var new null

想必只要 接触了 net core的小伙伴们 已经发现 @html.Action()方法 官方已经不提供支持了,转而使用 ViewComponents替代了,同时也增加了TagHelper。但是 如果想用以前的@Html.Action()方法,我们其实可以自己动手去实现它。

下面就开始 实现之旅吧!

1、创建 静态类 HtmlHelperViewExtensions,其命名空间为  Microsoft.AspNetCore.Mvc.Rendering。这样我们直接用@Html直接可以 使用Action方法了。

 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using System.Threading.Tasks;   namespace Microsoft.AspNetCore.Mvc.Rendering {     public static class HtmlHelperViewExtensions     {         public static IHtmlContent Action(this IHtmlHelper helper, string action, object parameters = null)         {             var controller = (string)helper.ViewContext.RouteData.Values["controller"];               return Action(helper, action, controller, parameters);         }           public static IHtmlContent Action(this IHtmlHelper helper, string action, string controller, object parameters = null)         {             var area = (string)helper.ViewContext.RouteData.Values["area"];               return Action(helper, action, controller, area, parameters);         }           public static IHtmlContent Action(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)         {             if (action == null)                 throw new ArgumentNullException("action");               if (controller == null)                 throw new ArgumentNullException("controller");                 var task = RenderActionAsync(helper, action, controller, area, parameters);               return task.Result;         }           private static async Task<IHtmlContent> RenderActionAsync(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)         {             // fetching required services for invocation             var serviceProvider = helper.ViewContext.HttpContext.RequestServices;             var actionContextAccessor = helper.ViewContext.HttpContext.RequestServices.GetRequiredService<IActionContextAccessor>();             var httpContextAccessor = helper.ViewContext.HttpContext.RequestServices.GetRequiredService<IHttpContextAccessor>();             var actionSelector = serviceProvider.GetRequiredService<IActionSelector>();               // creating new action invocation context             var routeData = new RouteData();             foreach (var router in helper.ViewContext.RouteData.Routers)             {                 routeData.PushState(router, nullnull);             }             routeData.PushState(nullnew RouteValueDictionary(new { controller = controller, action = action, area = area }), null);             routeData.PushState(nullnew RouteValueDictionary(parameters ?? new { }), null);               //get the actiondescriptor             RouteContext routeContext = new RouteContext(helper.ViewContext.HttpContext) { RouteData = routeData };             var candidates = actionSelector.SelectCandidates(routeContext);             var actionDescriptor = actionSelector.SelectBestCandidate(routeContext, candidates);               var originalActionContext = actionContextAccessor.ActionContext;             var originalhttpContext = httpContextAccessor.HttpContext;             try             {                 var newHttpContext = serviceProvider.GetRequiredService<IHttpContextFactory>().Create(helper.ViewContext.HttpContext.Features);                 if (newHttpContext.Items.ContainsKey(typeof(IUrlHelper)))                 {                     newHttpContext.Items.Remove(typeof(IUrlHelper));                 }                 newHttpContext.Response.Body = new MemoryStream();                 var actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor);                 actionContextAccessor.ActionContext = actionContext;                 var invoker = serviceProvider.GetRequiredService<IActionInvokerFactory>().CreateInvoker(actionContext);                 await invoker.InvokeAsync();                 newHttpContext.Response.Body.Position = 0;                 using (var reader = new StreamReader(newHttpContext.Response.Body))                 {                     return new HtmlString(reader.ReadToEnd());                 }             }             catch (Exception ex)             {                 return new HtmlString(ex.Message);             }             finally             {                 actionContextAccessor.ActionContext = originalActionContext;                 httpContextAccessor.HttpContext = originalhttpContext;                 if (helper.ViewContext.HttpContext.Items.ContainsKey(typeof(IUrlHelper)))                 {                     helper.ViewContext.HttpContext.Items.Remove(typeof(IUrlHelper));                 }             }         }     } }

  

2、 在Startup中的 ConfigureServices 方法添加:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor();

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

(备注:因为net core 默认不将IHttpContextAccessor,IActionContextAccessor 依赖注入,所以需要手动进行依赖注入)

3、在页面中,我们就可以直接用 @Html.Action()方法 直接请求 控制器的方法了。          

4、小结:如今微软官方已经提供了 新的 TagHelper、View components 来替代之前的写法。这个教程只适用于对视图层不想做更变的小伙伴使用。如果 是新项目的,还是建议使用 View components!

转自:https://blog.csdn.net/huanghuangtongxue/article/details/78987833

标签:Core,Asp,helper,action,controller,Html,var,new,null
From: https://www.cnblogs.com/Alex80/p/17621891.html

相关文章

  • 【JavaScript36】HTML DOM创建/插入/删除/替换元素
    createElement创建元素document.createElement()可以创建一个元素document.createTextNode()创建一个文本节点appendChild()方法可向节点的子节点列表的末尾添加新的子节点。<divid="demo"><pid="p1">这是文本内容</p></div><script>//div下添加一个子元......
  • 【JavaScript35】innerText 和 innerHTML
    获取内容时innerHTML从对象的起始位置到终止位置的全部内容,还包括HTML标签。innerText会去掉标签的内容。innerText和innerHTML获取内容示例<divid="demo"><pid="p1"><strong>这是文本内容</strong></p>helloworld!</div><script>......
  • solr的master-slave和Multiple Cores
    Solrmulticore配置April21st,2011绚丽也尘埃LeaveacommentGotocommentsSolr继续学习中,感觉Solr的multicore主要用途有两个:1、充分利用服务器资源。在一台服务器上部署不用的搜索应用。2、提高一个应用服务能力,在服务器上同时部署同一个应用的多个core,这些core共用一份索......
  • ASP.NET 使用Ajax
    本文将介绍在ASP.NET中如何方便使用Ajax,第一种当然是使用jQuery的ajax,功能强大而且操作简单方便,第二种是使用.NET封装好的ScriptManager。$.ajax向普通页面发送get请求这是最简单的一种方式了,先简单了解jQueryajax的语法,最常用的调用方式是这样:$.ajax({settings});有几个常用......
  • asp.net blazor 新手问题
    刚开始学asp,发布程序其他电脑不能访问:http://localhost:5000和http://127.0.0.1:5000可以访问。但是http://192.168.0.20:5000 不可以。192.168.0.20是笔记本电脑的ip。在笔记本和局域网电脑访问http://192.168.0.20:5000都不可以。 排查思路:网络问题,http网络访问全流程......
  • HTMLParser(一个比较流行的html代码解析、处理开源项目)学习,总结
    主页:http://htmlparser.sourceforge.net/ HtmlParser初步研究bylostfire这两天准备做一些网站编程的工作,于是对HtmlParse小研究了一下,目的是快速入手,而不是深入研究,做了一下整理,和大家共同讨论一下。一,数据组织分析:HtmlParser主要靠Node、AbstractNode和Tag来表达Html,因为Remar......
  • 借助Aspose.Html 将 HTML 模板与 XML 或 JSON 合并
    在现代网络开发中,内容和表示的分离是一个基本原则。HTML模板提供了一种定义网页结构和布局的便捷方法,而JSON和XML数据格式通常用于存储和传输结构化信息。结合这些技术,开发人员可以根据外部源的数据动态生成HTML内容。在这篇博文中,我们将探讨如何在Java中将HTML模板与JS......
  • 使用Aspose.BarCode,在 Python 中扫描条码
    条形码是机器可读的数据表示形式,由平行线或几何图案直观地表示。它们提供了一种快速准确的方法来存储和检索信息,例如产品详细信息、库存代码或跟踪号码。条形码有多种类型,包括UPC、EAN、QR码等。每种类型都有特定的结构和编码机制。在这篇博文中,我们将学习如何构建高性能的Python......
  • 构建含wkhtmltopdf的jre镜像
    目录官网地址字体下载支持wkhtmlto的镜像Dockerfile构建镜像验证wkhtmltopdf官网地址https://wkhtmltopdf.org/字体下载https://github.com/StellarCN/scp_zh/tree/master/fonts支持wkhtmlto的镜像https://hub.docker.com/r/aantonw/alpine-wkhtmltopdf-patched-qt将......
  • 【HMS Core】支付失败报错60004
    【关键字】报错、60004、developerPayload、支付服务【问题描述1】集成应用内支付服务,发现部门用户支付失败报错60004【问题分析】根据官网错误码,是由于支付接口访问过频造成的那么,这个异常是针对用户的单台设备访问频次过高还是针对APP调用频次过高,如果是单台设备,这个频次大概是多......