ASP.NET MVC在URL中隐藏内容目录 [英] ASP.NET MVC Hide Content Directory in url
问题描述
有人要求我查看是否有可能阻止Content目录在Asp.Net MVC 3.0应用程序中显示为url的一部分.例如目前,当我要在Content文件夹的子目录中查看图像时,URL如下:
I've been asked to see if it's possible to prevent the Content directory from appearing as part of the url in an Asp.Net MVC 3.0 application. For example at present when I want to view an image in the sub directory of the Content folder the url is as follows:
http://localhost:[port]/Content/sub/test.bmp
我们希望将其简单显示如下:
While we are looking to display it simply as follows:
http://localhost:[port]/sub/test.bmp
Test.bmp实际上仍将存在于我们仅希望隐藏内容"部分的服务器上的内容"文件夹的子目录中.
Test.bmp will still physically exist in the sub directory of the Content folder on the server we just want to hide the Content part.
有什么建议吗?我可以看到掩盖控制器的方法,但看不到目录.
Any suggestions? I can see ways of masking controllers but not directories.
推荐答案
解决方案如下(目前这只是准系统代码,需要整理):
Solution is as follows (this is just the barebones code at the moment and needs to be tidied up):
已将此路由添加到Global.asax:
Added this route to Global.asax :
routes.MapRoute("Content",
"{dir}/{file}",
new { controller = "Content", action = "LoadContent"});
添加了此控制器来处理请求:
Added this controller to handle the request:
namespace demos
{
public class ContentController : Controller
{
public ActionResult LoadContent(string dir, string file)
{
string fileName = Server.MapPath(Url.Content("~/Content/" + dir))
fileName += "\\" + file;
// stream file if exists
FileInfo info = new FileInfo(fileName);
if (info.Exists)
return File(info.OpenRead(), MimeType(fileName));
// else return null - file not found
return null;
}
private string MimeType(string filename)
{
string mime = "application/octetstream";
var extension = Path.GetExtension(filename);
if (extension != null)
{
RegistryKey rk = Registry.ClassesRoot.OpenSubKey(extension.ToLower());
if (rk != null && rk.GetValue("Content Type") != null)
mime = rk.GetValue("Content Type").ToString();
}
return mime;
}
}
}
这篇关于ASP.NET MVC在URL中隐藏内容目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!