• [ASP.NET Core]ASP.NET Core应用程序开发中如何使用@Html.Action?


    其中IHtmlHelper@Html.Action另一个静态扩展方法实现代码

    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
    {
        /// <summary>
        /// https://blog.csdn.net/WuLex/article/details/122761955
        /// </summary>
        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)
            {
                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>();
    
                var routeData = new RouteData();
                foreach (var router in helper.ViewContext.RouteData.Routers)
                {
                    routeData.PushState(router, null, null);
                }
                routeData.PushState(null, new RouteValueDictionary(new { controller = controller, action = action, area = area }), null);
                routeData.PushState(null, new RouteValueDictionary(parameters ?? new { }), null);
    
                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));
                    }
                }
            }
        }
        
    }

     在Startup中的 ConfigureServices 方法添加:

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

                services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

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

    https://codedefault.com/s/how-can-i-use-html-action-in-aspnet-core-application

    https://blog.csdn.net/weixin_33554514/article/details/117835148

     
    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; namespaceMicrosoft.AspNetCore.Mvc.Rendering { publicstaticclassHtmlHelperViewExtensions { 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) thrownew ArgumentNullException("action"); if (controller == null) thrownew 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) { 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>(); var routeData = new RouteData(); foreach (var router in helper.ViewContext.RouteData.Routers) { routeData.PushState(router, null, null); } routeData.PushState(null, new RouteValueDictionary(new { controller = controller, action = action, area = area }), null); routeData.PushState(null, new RouteValueDictionary(parameters ?? new { }), null); 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)) { returnnew HtmlString(reader.ReadToEnd()); } } catch (Exception ex) { returnnew 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)); } } } } }
  • 相关阅读:
    mysql 5.7.28 中GROUP BY报错问题 SELECT list is not in GROUP BY clause and contains no
    mysql 的root 用户无法授权,navicat 远程授权提示1044解决方案
    Java equals(),== 和 hashcode()
    一键批处理图片的脚本(将指定目录中的图片处理成要求的分辨率)
    Anaconda环境下GPT2-Chinese的基本使用记录
    Ubuntu WSL 下编译并使用OpenJDK12
    SSM项目下Druid连接池的配置及数据源监控的使用
    《MySql必知必会》笔记整理
    Java面试题整理
    SpringBoot 访问树莓派上的MySql
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/16371021.html
Copyright © 2020-2023  润新知