MVC路由重写允许访问静态资源

webconfig 更改
<modules runAllManagedModulesForAllRequests="true">

路由重写
routes.MapRoute(
name: "File",
url: "bexi/M2/vip/{id}.txt",
defaults: new { controller = "File", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Maticsoft.WebShop.Controllers" }
);

添加FileController
public ActionResult Index(string id)
{
string url = "~/Content/txt/" + id + ".txt";

var fileName = Server.MapPath(url);

var result = FileHelper.ReadFile(fileName);

return Content(result);
}

url访问:bexi/M2/vip/test.txt

参考:
https://www.haolizi.net/example/view_1439.html
https://blog.csdn.net/weixin_33843409/article/details/93979638


通过url访问文件(静态资源)
public ContentResult TxtStaticFile(string id)
{
string url = "~/Content/txt/"+id+".txt";

var fileName = Server.MapPath(url);
var name = Path.GetFileName(fileName);
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
//使用StreamReader类来读取文件
sr.BaseStream.Seek(0, SeekOrigin.Begin);
// 从数据流中读取每一行,直到文件的最后一行
string tmp = sr.ReadLine();
string result = string.Empty;
while (tmp != null)
{
result += Templete;
tmp = sr.ReadLine();
}
//关闭此StreamReader对象
sr.Close();
fs.Close();
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(result, Formatting.None));
}

路由访问html

routes.MapRoute(
name: "File2",
url: "beikangxi/M2/vipcenter/{id}.html",
defaults: new { controller = "File", action = "Web", id = UrlParameter.Optional },
namespaces: new[] { "Maticsoft.WebShop.Controllers" }
);

routes.MapRoute(
name: "File2",
url: "beixi/M2/vip/{id}.html",
defaults: new { controller = "File", action = "Web", id = UrlParameter.Optional },
namespaces: new[] { "Maticsoft.WebShop.Controllers" }
);

public ActionResult Web(string id)
{
string url = "~/Content/txt/" + id + ".html";

return Redirect(url);
}

bexi/M2/vip/test.txt

参考
https://www.cnblogs.com/searchbaidu/p/5857522.html
https://blog.csdn.net/milijiangjun/article/details/100543418

此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。

原文地址:https://www.cnblogs.com/shy1766IT/p/15137204.html