如何将另一个目录中的 html 文件作为 ActionResult 提供
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10830212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serve html file from another directory as ActionResult
提问by Aran Mulholland
I have a specialised case where I wish to serve a straight html file from a Controller Action.
我有一个特殊的案例,我希望从控制器操作提供一个直接的 html 文件。
I want to serve it from a different folder other than the Views folder. The file is located in
我想从 Views 文件夹以外的其他文件夹中提供它。该文件位于
Solution\Html\index.htm
And I want to serve it from a standard controller action. Could i use return File? And how do I do this?
我想从标准控制器操作中提供它。我可以使用返回文件吗?我该怎么做?
回答by Wahid Bitar
Check this out :
看一下这个 :
public ActionResult Index()
{
return new FilePathResult("~/Html/index.htm", "text/html");
}
回答by lucask
If you want to render this index.htm file in the browser then you could create controller action like this:
如果你想在浏览器中渲染这个 index.htm 文件,那么你可以像这样创建控制器动作:
public void GetHtml()
{
var encoding = new System.Text.UTF8Encoding();
var htm = System.IO.File.ReadAllText(Server.MapPath("/Solution/Html/") + "index.htm", encoding);
byte[] data = encoding.GetBytes(htm);
Response.OutputStream.Write(data, 0, data.Length);
Response.OutputStream.Flush();
}
or just by:
或者只是通过:
public ActionResult GetHtml()
{
return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html");
}
So lets say this action is in Homecontroller and some user hits http://yoursite.com/Home/GetHtmlthen index.htm will be rendered.
所以让我们说这个动作在Home控制器中,一些用户点击http://yoursite.com/Home/GetHtml然后 index.htm 将被呈现。
EDIT: 2 other methods
编辑:2种其他方法
If you want to see raw html of index.htmin the browser:
如果您想在浏览器中查看index.htm 的原始 html :
public ActionResult GetHtml()
{
Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition { Inline = true, FileName = "index.htm"}.ToString());
return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/plain");
}
If you just want to download file:
如果您只想下载文件:
public FilePathResult GetHtml()
{
return File(Server.MapPath("/Solution/Html/") + "index.htm", "text/html", "index.htm");
}
回答by om471987
I extended wahid's answer to create HtmlResult
我扩展了 wahid 的答案以创建 HtmlResult
Create Html Result which extends FilePathResult
创建扩展 FilePathResult 的 Html Result
public class HtmlResult : FilePathResult
{
public HtmlResult(string path)
: base(path, "text/html")
{
}
}
Created static method on controller
在控制器上创建静态方法
public static HtmlResult Html(this Controller controller, string path)
{
return new HtmlResult(path);
}
used like we return view
像我们返回视图一样使用
public HtmlResult Index()
{
return this.Html("~/Index.html");
}
Hope it helps
希望能帮助到你
回答by Ognyan Dimitrov
I want put my two cents in. I have found this most terse and it is there already :
我想把我的两分钱放进去。我发现这个最简洁,它已经在那里了:
public ActionResult Index()
{
var encoding = new System.Text.UTF8Encoding();
var html = ""; //get it from file, from blob or whatever
return this.Content(html, "text/html; charset=utf-8");
}
回答by Jason
Alternative approach if using .net core is to use a FileProvider. The files could be in a folder or embedded at compile time.
如果使用 .net 核心,另一种方法是使用 FileProvider。这些文件可以在一个文件夹中或在编译时嵌入。
In this example we will use embedded files.
在本例中,我们将使用嵌入文件。
Add a folder in your project let's say assets, in it create a file myfile.html, add some basic html to the file say
在您的项目中添加一个文件夹,比如说资产,在其中创建一个文件 myfile.html,向文件添加一些基本的 html 说
<html>
<head>
<title>Test</title>
</head>
<body>
Hello World
</body>
</html>
Right click on the new file (assuming you are in visual studio) select properties, in the properties screen / build action, select embedded resource. It will add the file to the csproj file.
右键单击新文件(假设您在 Visual Studio 中)选择属性,在属性屏幕/构建操作中,选择嵌入资源。它会将文件添加到 csproj 文件中。
Right click on your project, edit your csproj file. Check that your property group contains the following:
右键单击您的项目,编辑您的 csproj 文件。检查您的属性组是否包含以下内容:
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
If not please add it. The csproj should also contain the newly created html file as:
如果没有,请添加它。csproj 还应包含新创建的 html 文件,如下所示:
<ItemGroup>
<EmbeddedResource Include="assets\myfile.html" />
</ItemGroup>
To read the file in your controller and pass it to the client requires a file provider which is added to the startup.cs
要读取控制器中的文件并将其传递给客户端需要添加到 startup.cs 的文件提供程序
Edit your startup.cs make sure it includes the HostingEnvironment:
编辑您的 startup.cs 确保它包含 HostingEnvironment:
private readonly IHostingEnvironment HostingEnvironment;
public Startup(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
Then create a file provider and make it a service that can be injected at runtime. Create it as follows:
然后创建一个文件提供程序并使其成为可以在运行时注入的服务。创建如下:
var physicalProvider = HostingEnvironment.ContentRootFileProvider;
var manifestEmbeddedProvider =
new ManifestEmbeddedFileProvider(Assembly.GetEntryAssembly());
var compositeProvider =
new CompositeFileProvider(physicalProvider, manifestEmbeddedProvider);
services.AddSingleton<IFileProvider>(compositeProvider);
To serve the file go to your controller, use dependency injection to get the FileProvider, create a new service and serve the file. To do this, start with dependency injection by adding the provider to your constructor.
要将文件提供给您的控制器,使用依赖注入来获取 FileProvider,创建一个新服务并提供文件。为此,首先通过将提供程序添加到构造函数来进行依赖注入。
IFileProvider _fileProvider;
public MyController(IFileProvider fileProvider)
{
this._fileProvider = fileProvider;
}
Then use the file provider in your service
然后在您的服务中使用文件提供程序
[HttpGet("/myfile")]
[Produces("text/html")]
public Stream GetMyFile()
{
// Use GetFileInfo to get details on the file passing in the path added to the csproj
// Using the fileInfo returned create a stream and return it.
IFileInfo fileinfo = _fileProvider.GetFileInfo("assets/myfile.html");
return fileinfo.CreateReadStream();
}
For more info see ASP .Net Core file provider sampleand the Microsoft documentation here.
有关详细信息,请参阅 ASP .Net Core 文件提供程序示例和此处的 Microsoft 文档。
回答by Abhijit_K
Can you read the html file in a string and return it in action? It is rendered as Html page as shown below:
你能读取字符串中的 html 文件并在操作中返回它吗?它呈现为 Html 页面,如下所示:
public string GetHtmlFile(string file)
{
file = Server.MapPath("~/" + file);
StreamReader streamReader = new StreamReader(file);
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
Home/GetHtmlFile?file=Solution\Html\index.htm
Home/GetHtmlFile?file=Solution\Html\index.htm
If the destination or storage mechanism of HTML files is complicated then you can you Virtual path provider
如果 HTML 文件的目的地或存储机制很复杂,那么您可以使用Virtual path provider