Asp.Net Core 2.0 之旅---@Html.Action
原文: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的更多相关文章
- Asp.Net Core 2.0 之旅---在Ubuntu上部署WEB应用程序
1.Ubuntu 上 安装NET Core 2.0 SDK 第一步的安装,微软大佬已经写的非常详细了=>直达链接,按照教程来即可. 2.将我们的WEB 发布到一个文件夹,将这个文件夹打包成 压缩 ...
- .NET跨平台之旅:将示例站点从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0
终于将“.NET跨平台之旅”的示例站点 about.cnblogs.com 从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0 ,经历了不少周折,在这篇博文中记录一下. 从 AS ...
- .NET跨平台之旅:将示例站点升级至ASP.NET Core 1.0
北京时间6月28日凌晨,微软发布了 .NET Core 1.0,详见新闻 .NET Core 1.0 正式发布了 ,ASP.NET Core 1.0 也随之一起发布了. 紧跟这次发布,我们将跑在 Li ...
- ASP.NET Core 1.0 中使用 Log 日志配置
https://github.com/aspnet/Logging https://docs.asp.net/en/latest/fundamentals/logging.html ASP.NET C ...
- .NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布
众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL)系统上的一流开发平台选项.这个团队已经一起工作好几个月了,RHEL对.NET有许多需求.今天在 ...
- ASP.NET Core 1.0 开发记录
官方资料: https://github.com/dotnet/core https://docs.microsoft.com/en-us/aspnet/core https://docs.micro ...
- 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 ...
- 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>, ...
- ASP.NET Core 1.0中实现文件上传的两种方式(提交表单和采用AJAX)
Bipin Joshi (http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx) Uplo ...
随机推荐
- vlookup实战_英语单词更新
https://study.163.com/provider/400000000398149/index.htm?share=2&shareId=400000000398149( 欢迎关注博主 ...
- Android 定义和使用样式
如图,在stryle.xml中定义样式 然后可以在布局文件中使用样式
- Hibernate 自动更新表出错 More than one table found in namespace
报错:Caused by: org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table f ...
- Qt坐标系以及自定义可移动控件
1.效果 黑色这个控件是自定义的,可以在界面拖动 2.新建控件的Qt类,父类是QWidget,带ui的,Control.h #ifndef CONTROL_H #define CONTROL_H #i ...
- WPF窗体应用程序开发
1.Window:登录窗口.主窗体.消息框 2.UserControl:业务界面.消息框(如果使用UC来实现,则需要做特殊的处理,比如中断功能如何处理?)(显示一个UC,必须将其添加到容器中,所以&l ...
- 游戏开发中伪随机正态分布JavaScript
在游戏开发中经常遇到随机奖励的情况,一般会采取先生成数组,再一个一个取的方式发随机奖励. 下面是js测试正态分布代码: <!DOCTYPE html> <html lang=&quo ...
- 浅出讲解:php的socket通信
原文地址:https://www.cnblogs.com/aipiaoborensheng/p/6708963.html 对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发 ...
- thinkphp5 引用 phpass加密算法
引入phpass thinkPHP5 放到扩展目录里 自动加载配置 直接实例化 // 初始化散列器为不可移植(这样更安全) $PasswordHashs = new \PasswordHashs(8, ...
- 移动架构之MVP框架
MVP是在开发中常用的框架,要了解其原理,先要从了解MVC开始,这里就对MVP框架做一个简单的介绍 MVC MVC为Model,View与Controllor的缩写 Model:业务逻辑和实体模型 V ...
- 各种 Java Thread State 分析
转自:https://www.cnblogs.com/zhengyun_ustc/archive/2013/03/18/tda.html 1,线程状态为“waiting for monitor ent ...