【问题标题】:Render AngularJs index.html in an ASP.NET Core MVC view在 ASP.NET Core MVC 视图中渲染 AngularJs index.html
【发布时间】:2020-11-12 14:59:23
【问题描述】:

我目前正在使用以下技术迁移网络应用:

  1. ASP.NET MVC
  2. AngularJs
  3. 吞咽
  4. Azure 云服务

到:

  1. ASP.NET Core MVC
  2. AngularJs
  3. 网页包
  4. Azure 应用服务

迁移的应用程序正确地捆绑并提供 AngularJs index.html 到 wwwroot。 目前,我需要向 ASP.NET Core MVC 应用程序添加两个视图并将index.html 注入这些视图。

我不知道该怎么做:

  • 注入 index.html
  • 将其中一个视图设为启动视图。

终于有了一个 URL 模式:

localhost/View1/#/angularJs-state 

localhost/View2/#/angularJs-state

wwwroot:

首页:

public class BaseController : Controller
{
    public IActionResult Index()
    {
        return View("portal");
    }
}

第一个视图:

 public class PortalController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Startup.cs

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(name: "portal",
            pattern: "Portal",
            defaults: new { controller = "Portal", action = "Index" });
            endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Base}/{action=Index}/{id?}");
        });
  • 第一个视图正确显示,但没有视图名称 网址。
  • 是否可以在 cshtml 中从 wwwroot 呈现 index.html 使用@html.Partial 查看?

【问题讨论】:

  • 在我看来,最简单的方法是将所有 index.html 代码复制到默认视图中,而不是在视图中呈现 index.html。由于 index.html 包含整个 html 格式,并且视图也包含这个。
  • webpack 更新 index.html 以添加包含捆绑文件的脚本,具体何时复制?

标签: angularjs webpack asp.net-core-mvc


【解决方案1】:

根据您的描述,如果您想在视图中渲染html页面,我建议您可以在mvc中编写一个自定义渲染方法,并将索引文件作为文件结果返回给mvc视图。

更多细节,您可以参考以下代码:

1.创建渲染扩展方法:

public static class HtmlHelperViewExtensions
{
    public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, object parameters = null)
    {
        var controller = (string)helper.ViewContext.RouteData.Values["controller"];
        return RenderAction(helper, action, controller, parameters);
    }

    public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, string controller, object parameters = null)
    {
        var area = (string)helper.ViewContext.RouteData.Values["area"];
        return RenderAction(helper, action, controller, area, parameters);
    }

    public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
    {
        if (action == null)
            throw new ArgumentNullException(nameof(controller));
        if (controller == null)
            throw new ArgumentNullException(nameof(action));

        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 currentHttpContext = helper.ViewContext.HttpContext;
        var httpContextFactory = GetServiceOrFail<IHttpContextFactory>(currentHttpContext);
        var actionInvokerFactory = GetServiceOrFail<IActionInvokerFactory>(currentHttpContext);
        var actionSelector = GetServiceOrFail<IActionDescriptorCollectionProvider>(currentHttpContext);

        // creating new action invocation context
        var routeData = new RouteData();
        var routeParams = new RouteValueDictionary(parameters ?? new { });
        var routeValues = new RouteValueDictionary(new { area, controller, action });
        var newHttpContext = httpContextFactory.Create(currentHttpContext.Features);

        newHttpContext.Response.Body = new MemoryStream();

        foreach (var router in helper.ViewContext.RouteData.Routers)
            routeData.PushState(router, null, null);

        routeData.PushState(null, routeValues, null);
        routeData.PushState(null, routeParams, null);

        var actionDescriptor = actionSelector.ActionDescriptors.Items.First(i => i.RouteValues["Controller"] == controller && i.RouteValues["Action"] == action);
        var actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor);

        // invoke action and retreive the response body
        var invoker = actionInvokerFactory.CreateInvoker(actionContext);
        string content = null;

        await invoker.InvokeAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                content = task.Exception.Message;
            }
            else if (task.IsCompleted)
            {
                newHttpContext.Response.Body.Position = 0;
                using (var reader = new StreamReader(newHttpContext.Response.Body))
                    content = reader.ReadToEnd();
            }
        });

        return new HtmlString(content);
    }

    private static TService GetServiceOrFail<TService>(HttpContext httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));

        var service = httpContext.RequestServices.GetService(typeof(TService));

        if (service == null)
            throw new InvalidOperationException($"Could not locate service: {nameof(TService)}");

        return (TService)service;
    }
}

2.添加控制器方法如下:

    public IActionResult IndexFile()
    {
        return File("index.html", "text/html");
    }

3.在视图中添加以下代码:

@Html.RenderAction("IndexFile", "Yourcontrollername")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多