我怎样才能读取ASP.Net MVC中的文件的内容?(How can I read the contents of a file in ASP.Net MVC?)

编程入门 行业动态 更新时间:2024-10-18 06:06:15
我怎样才能读取ASP.Net MVC中的文件的内容?(How can I read the contents of a file in ASP.Net MVC?)

我有一个ASP.Net MVC控制器操作,需要返回一个json结果(它实际上是jsonp,但这不重要),它包含另一个html文件的内容。 所以基本上,我想这样做:

[JsonpFilter] public JsonResult GetHeader() { var html = System.IO.File.ReadAllText("/htm/external/header.htm"); return Json(new { html = html }, JsonRequestBehavior.AllowGet); }

但是,它没有找到正确的文件。 它在C目录下查找(无法找到'C:\ htm \ external \ header.htm'路径的一部分),当我想要它查看服务器的根目录(当然是加上/ htm / external)。

我怎样才能读取这个文件? 它是外部可用的,所以我想我可以为它创建一个单独的Web请求,但似乎我应该能够直接定位它。

I have an ASP.Net MVC controller action that needs to return a json result (it's actually jsonp, but that's not important) that contains the contents of another html file. So basically, I want to do this:

[JsonpFilter] public JsonResult GetHeader() { var html = System.IO.File.ReadAllText("/htm/external/header.htm"); return Json(new { html = html }, JsonRequestBehavior.AllowGet); }

However, it's not finding the right file. It's looking in the C directory (Could not find a part of the path 'C:\htm\external\header.htm'), when I want it to look at the server's root (plus /htm/external, of course).

How can I read this file in? It's externally available, so I guess I could make a separate web request for it, but it seems like I should be able to target it directly.

最满意答案

您可以使用HttpServerUtility.MapPath方法解析一个虚拟路径到其物理位置:

string html = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/htm/external/header.htm"));

You can resolve a virutal path to its physical location using the HttpServerUtility.MapPath Method:

string html = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/htm/external/header.htm"));

更多推荐

html,htm,external,电脑培训,计算机培训,IT培训"/> <meta name="description

本文发布于:2023-08-06 05:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   内容   MVC   ASP   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!