简体   繁体   English

如何从Asp.Net核心控制器返回嵌入式静态html文件?

[英]How to return an embedded static html file from an Asp.Net Core Controller?

I have the following configuration: 我有以下配置:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDefaultFiles();

        app.UseFileServer(new FileServerOptions
        {
            FileProvider = new EmbeddedFileProvider(typeof(Startup).Assembly, typeof(Startup).Namespace + ".WebApp"),
            RequestPath = string.Empty
        });

        app.UseCors("CorsPolicy");

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "angular",
                defaults: new {controller = "Angular", action = "Index"},
                template: "{*url}");
        });
    }

My Angular project files are in the namespace MyNamespace.WebApp . 我的Angular项目文件位于名称空间MyNamespace.WebApp

My AngularController and Startup classes are in the namespace MyNamespace 我的AngularControllerStartup类位于名称空间MyNamespace

When I don't use MVC and access http://localhost:8000 it loads the index.html file in the WebApp folder. 当我不使用MVC并访问http:// localhost:8000时,它将在WebApp文件夹中加载index.html文件。 Now for all other requests (for example /action ) I have mapped it to the AngularController , which looks as follows: 现在,对于所有其他请求(例如/action ),我已将其映射到AngularController ,其外观如下:

public class AngularController : Controller
{
    public IActionResult Index() {
        return View("/index.html");
    }
}

I have debugged and verified that the request does come to AngularController.Index() and returns View("/index.html") . 我已经调试并验证了请求确实到达了AngularController.Index()并返回View("/index.html") But after that I get a 500 Error. 但是之后,我得到了500错误。 I'm guessing because it cannot find the view file. 我在猜测,因为它找不到视图文件。

How do I let MVC know to fetch the index.html file from the embedded files? 如何让MVC知道从嵌入式文件中获取index.html文件?

I've tried the following: 我尝试了以下方法:

return View("~/index.html");
return View("index.html");
return View("~/../index.html");
return View("../index.html");
return View("~/WebApp/index.html");
return View("WebApp/index.html");

None of these work. 这些都不起作用。 Probably I've missed a step? 可能我错过了一步?

In this example, I've tried to create an HTML file with the name htmlpage.html in the path Views/Home/htmlpage.html . 在此示例中,我尝试在路径Views/Home/htmlpage.html创建一个名称为htmlpage.html的HTML文件。

In the file Index.cshtml (path: Views/Home/Index.cshtml ): 在文件Index.cshtml (路径: Views/Home/Index.cshtml ):

@using Microsoft.AspNetCore.Hosting
@using System.IO
@inject IHostingEnvironment environment
@{ 
    string htmlPath = "Views/Home/htmlpage.html";
}

@Html.Raw(File.ReadAllText(System.IO.Path.Combine(environment.ContentRootPath, htmlPath)))

In the file htmlpage.html : htmlpage.html文件中:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>bar</title>
</head>
<body>
    <h3>foo</h3>
</body>
</html>

Test: 测试:

1


This way doesn't require: app.UseDefaultFiles(); 这种方式不需要: app.UseDefaultFiles(); and app.UseFileServer(...); app.UseFileServer(...);

My solution was to configure a controller that would use an EmbeddedFileProvider and fetch the contents of the embedded file as follows: 我的解决方案是配置一个控制器,该控制器将使用EmbeddedFileProvider并按以下方式获取嵌入式文件的内容:

public AngularController: Controller
{
    private IAppSettings appSettings;

    public AngularController(IAppSettings appSettings)
    {
        this.appSettings = appSettings;
    }

    public IActionResult Index()
    {
        var fileProvider = new EmbeddedFileProvider(this.appSettings.WebAssembly, this.appSettings.WebNamespace);
        var contents = this.fileProvider.GetDirectoryContents(string.Empty);

        IFileInfo index = null;
        foreach (var file in contents)
        {
            if (file.Name.Equals("index.html"))
            {
                index = file;
                break;
            }
        }

        if (index == null)
        {
            throw new Exception("'index.html' not found");
        }

        var reader = new StreamReader(index.CreateReadStream());
        var text = reader.ReadToEnd();
        return this.Content(text, "text/html");
    }
}

The Assembly and Namespace of the embedded files are provided using dependency injection to make it more generic. 嵌入文件的AssemblyNamespace使用依赖项注入来提供,以使其更加通用。 You could also hard code it into the controller. 您也可以将其硬编码到控制器中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core - 无法在控制器内使用 C# StreamReader 读取静态 HTML 文件 - ASP.NET Core - Not able to read static HTML file using C# StreamReader inside Controller 从asp.net核心中的资源读取嵌入式文件 - Read embedded file from resource in asp.net core 如何从 ASP.NET Core MVC 中的一个控制器调用或返回另一个控制器的视图 - How to call or return the view of another controller from one controller in ASP.NET Core MVC 返回自定义ValidationResult并从Asp.Net Core中的控制器访问它 - Return Custom ValidationResult and access it from controller in Asp.Net Core 如何从asp.net core mvc html helper静态方法中的html helper上下文中获取urlHelper - How to get the urlHelper from html helper context in asp.net core mvc html helper static method 如何使用 controller 或在 ASP.NET Core MVC 中查看 wwwroot 文件夹中的 index.html 文件 - How to render index.html file that is in wwwroot folder using controller or view in ASP.NET Core MVC Asp.net 核心 3.1- 我如何从 Controller 返回到 Razor 页面? - Asp.net Core 3.1- How can I return from Controller to Razor Page? 如何从 ASP.Net Core Web API Controller 中的数据库返回关系数据 - How to return a relational data from DB in ASP.Net Core Web API Controller 如何在ASP.NET Core控制器中接收文件 - How to receive a file in ASP.NET Core controller 如何将文件上传到 ASP.NET 内核 controller? - How to upload file to an ASP.NET Core controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM