@Html. Action migration of ASP.

Source: Internet
Author: User
Tags httpcontext

Presumably, the small partners who have contacted Net core have found @html. The Action () method has not been supported by the official, instead using viewcomponents instead, and also adding taghelper. But if you want to use the previous @html.action () method, we can actually do it ourselves.

Let's start the journey here!

1, create static class Htmlhelperviewextensions, its namespace is Microsoft.AspNetCore.Mvc.Rendering. This way we can directly use the action method directly with @html.

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 para meters = 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 Co            Ntroller, 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 = is            A}), 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 HTMLSTR ING (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, in the startup of the Configureservices method add:

Services. Addsingleton<ihttpcontextaccessor, Httpcontextaccessor ();

Services. Addsingleton<iactioncontextaccessor, actioncontextaccessor> ();

(Note: Because net core does not inject ihttpcontextaccessor,iactioncontextaccessor dependency by default, manual dependency injection is required)

3, in the page, we can directly use the @Html. Action () method directly request the method of the controller.

4, Summary: Now the official Microsoft has provided a new taghelper, View components to replace the previous wording. This tutorial works only with small partners who don't want to do notconsistent on the layer. If this is a new project, it is recommended to use the View components!

Turn from: 78987833

@Html. Action migration of ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.