原文:Asp.Net Core 2.0 之旅---@Html.Action

版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。


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

下面就开始 实现之旅吧!

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

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, null, null);
}
routeData.PushState(null, new RouteValueDictionary(new { controller = controller, action = action, area = area }), null);
routeData.PushState(null, new 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!

Asp.Net Core 2.0 之旅---@Html.Action的更多相关文章

  1. Asp.Net Core 2.0 之旅---在Ubuntu上部署WEB应用程序

    1.Ubuntu 上 安装NET Core 2.0 SDK 第一步的安装,微软大佬已经写的非常详细了=>直达链接,按照教程来即可. 2.将我们的WEB 发布到一个文件夹,将这个文件夹打包成 压缩 ...

  2. .NET跨平台之旅:将示例站点从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0

    终于将“.NET跨平台之旅”的示例站点 about.cnblogs.com 从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0 ,经历了不少周折,在这篇博文中记录一下. 从 AS ...

  3. .NET跨平台之旅:将示例站点升级至ASP.NET Core 1.0

    北京时间6月28日凌晨,微软发布了 .NET Core 1.0,详见新闻 .NET Core 1.0 正式发布了 ,ASP.NET Core 1.0 也随之一起发布了. 紧跟这次发布,我们将跑在 Li ...

  4. ASP.NET Core 1.0 中使用 Log 日志配置

    https://github.com/aspnet/Logging https://docs.asp.net/en/latest/fundamentals/logging.html ASP.NET C ...

  5. .NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布

    众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL)系统上的一流开发平台选项.这个团队已经一起工作好几个月了,RHEL对.NET有许多需求.今天在 ...

  6. ASP.NET Core 1.0 开发记录

    官方资料: https://github.com/dotnet/core https://docs.microsoft.com/en-us/aspnet/core https://docs.micro ...

  7. ASP.NET 5 RC1 升级 ASP.NET Core 1.0 RC2 记录

    升级文档: Migrating from DNX to .NET Core Migrating from ASP.NET 5 RC1 to ASP.NET Core 1.0 RC2 Migrating ...

  8. ASP.NET 5 改名 ASP.NET Core 1.0

    今天,Scott Hanselman在其博客上宣布<ASP.NET 5 is dead - Introducing ASP.NET Core 1.0 and .NET Core 1.0>, ...

  9. ASP.NET Core 1.0中实现文件上传的两种方式(提交表单和采用AJAX)

    Bipin Joshi (http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx) Uplo ...

随机推荐

  1. 转: mysql的取整函数

    一.ROUND()函数用法 ROUND(X) -- 表示将值 X 四舍五入为整数,无小数位    ROUND(X,D) -- 表示将值 X 四舍五入为小数点后 D 位的数值,D为小数点后小数位数.若要 ...

  2. Win+数字快速启动/切换指定程序

    Windows键+数字,可以快速启动任务栏上的程序 按下按下Win+4桌面将切换到排序第4的程序:页也就是谷歌浏览器. 今天刚发现这个小功能.   文章来源:外星人来地球 欢迎关注,有问题一起学习欢迎 ...

  3. linux查看文件的编码格式的方法 set fileencoding

    查看文件编码在Linux中查看文件编码可以通过以下几种方式:1.在Vim中 可以直接查看文件编码:set fileencoding即可显示文件编码格式.如果你只是想查看其它编码格式的文件或者想解决 用 ...

  4. VS下设置dll环境变量目录的方法

    项目=>属性=>Debugging PATH=路径

  5. python方法未绑定错误

    相信 Python 程序员多多少少都和我一样遇到过 Method Unbound Error,直译过来就是 “方法未绑定错误”,虽然搜索之后知道了使用 @classmethod 这样的装饰起后就可以解 ...

  6. python线程池(转)

    ThreadPool: #! /usr/bin/env python # -*- coding: utf-8 -*- import threadpool import time def sayhell ...

  7. QDateTime QString

    QDateTime格式化  yyyy-MM-dd hh:mm:ss QString getFormatDateStr(QDateTime dateTimeParam) { qDebug() <& ...

  8. 19 Flutter 自定义AppBar 定义顶部Tab切换 底部Tab结合顶部Tab实现类似头条页面布局(27分36秒)

    Flutter AppBar自定义顶部导航按钮图标.颜色以及TabBar定义顶部Tab切换. leading:在标题前面显示的一个控件,在首页通常显示应用的logo:在其他界面通常显示为付汇按钮. t ...

  9. MySQL之二进制日志

    一.Binlog日志格式 根据日志定义的格式不一样,可以分为Statement格式.Row格式或者MIXED格式 mysql5.6----> | binlog_format | STATEMEN ...

  10. [Paper翻译]Scalable Lock-Free Dynamic Memory Allocation

    原文: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.87.3870&rep=rep1&type=pdf Abstr ...