MVC 5 - 提供静态 txt 文件,出现 404 错误
MVC 5 - Serve a static txt file giving 404 error
我必须在我的 mvc 5 站点的 url 中的这个路径中公开一个 txt 文件:www.mysite.com/home/somefile.txt
.Net MVC 抛出 404 错误。
我已经在 web.config
上添加了处理程序
<add name="MyTxt"
path="/home/riot.txt"
verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
我还需要为这项工作做些什么?
[编辑 1]
我创建了这样的路线
routes.MapRoute(
name: "FileRoute",
url: "home/txt.txt",
defaults: new { controller = "Home", action = "GetFile" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
然后我更改 web.config
<modules runAllManagedModulesForAllRequests="true">
这是我的控制器
public FileResult GetFile()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"riot.txt"));
string fileName = "riot.txt";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
它在 url 上抛出 404 错误:http://localhost:10021/home/riot.txt
[编辑 2] 在本例中我输入了正确的 home/riot.txt
之后,我输入了错误的路由模式。我工作。谢谢大家。
~/ 解析为应用程序根目录。
/ 解析为站点根目录。
Path="/Home/txt.txt"
使用这个 ~/
在 asp.net
中推荐
Path="~/Home/txt.txt"
您似乎有一个根可以捕获所有 /home
请求 - 这在 MVC 模板中很常见。最简单的方法是更改文件路径:
/files/test.txt
但是如果你想用/home
路径提供文件,你应该改变你的HomeController
的名字,或者努力工作:
- 例如在名为
GetTxt()
的主页中创建一个操作
在您的 home-route 之前使用此模式定义一条路线:
/home/txt.txt
通过在 system.webServer/modules
路径中设置 runAllManagedModulesForAllRequests
属性,为 web.config
中的所有请求启用 运行 所有模块:
但我不推荐这样做。
我必须在我的 mvc 5 站点的 url 中的这个路径中公开一个 txt 文件:www.mysite.com/home/somefile.txt
.Net MVC 抛出 404 错误。
我已经在 web.config
上添加了处理程序 <add name="MyTxt"
path="/home/riot.txt"
verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
我还需要为这项工作做些什么?
[编辑 1] 我创建了这样的路线
routes.MapRoute(
name: "FileRoute",
url: "home/txt.txt",
defaults: new { controller = "Home", action = "GetFile" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
然后我更改 web.config
<modules runAllManagedModulesForAllRequests="true">
这是我的控制器
public FileResult GetFile()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"riot.txt"));
string fileName = "riot.txt";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
它在 url 上抛出 404 错误:http://localhost:10021/home/riot.txt
[编辑 2] 在本例中我输入了正确的 home/riot.txt
之后,我输入了错误的路由模式。我工作。谢谢大家。
~/ 解析为应用程序根目录。
/ 解析为站点根目录。
Path="/Home/txt.txt"
使用这个 ~/
在 asp.net
Path="~/Home/txt.txt"
您似乎有一个根可以捕获所有 /home
请求 - 这在 MVC 模板中很常见。最简单的方法是更改文件路径:
/files/test.txt
但是如果你想用/home
路径提供文件,你应该改变你的HomeController
的名字,或者努力工作:
- 例如在名为
GetTxt()
的主页中创建一个操作 在您的 home-route 之前使用此模式定义一条路线:
/home/txt.txt
通过在
system.webServer/modules
路径中设置runAllManagedModulesForAllRequests
属性,为web.config
中的所有请求启用 运行 所有模块:
但我不推荐这样做。