我能想到的唯一解决方案是使用自定义控制器和路由来为您执行此操作。但这不是一个干净的解决方案。
首先,您需要一个带有 GetFile 操作方法的 PublicController 类。这假定所有文件都直接位于 public/content 文件夹中。处理文件夹会使事情变得更加复杂。
public class PublicController : Controller
{
private IDictionary<String, String> mimeTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{{"css", "text/css"}, {"jpg", "image/jpg"}};
public ActionResult GetFile(string file)
{
var path = Path.Combine(Server.MapPath("~/Content"), file);
if (!System.IO.File.Exists(path)) throw new HttpException(404, "File Not Found");
var extension = GetExtension(file); // psuedocode
var mimetype = mimeTypes.ContainsKey(extension) ? mimeTypes[extension] : "text/plain";
return File(path, mimetype);
}
}
现在,您只需要一条靠近路线列表底部的路线,如下所示:
routes.MapRoute("PublicContent", "{file}", new {controller = "Public", action = "GetFile"});
问题是,现在当您只输入一个控制器名称(如“Home”)而不是默认为 HomeController 上的 Index 操作方法时,它假定您要从内容目录下载一个名为“Home”的文件。因此,在文件路由之上,您需要为每个控制器添加一个路由,以便它知道获取 Index 操作。
routes.MapRoute("HomeIndex", "Home", new { controller = "Home", action = "Index" });
因此,解决此问题的一种方法是将路线更改为:
routes.MapRoute("PublicContent", "{file}.{extension}", new {controller = "Public", action = "GetFile"});
以及对此的操作方法:
public ActionResult GetFile(string file, string extension)
{
var path = Path.Combine(Server.MapPath("~/Content"), file + "." + extension);
if (!System.IO.File.Exists(path)) throw new HttpException(404, "File Not Found");
var mimetype = mimeTypes.ContainsKey(extension) ? mimeTypes[extension] : "text/plain";
return File(path, mimetype);
}
就像我说的,这假设所有文件都在内容目录中,而不是在子文件夹中。但是,如果你想做 Content/css/site.css 之类的子文件夹,你可以像这样添加你的路由:
routes.MapRoute("PublicContent_sub", "{subfolder}/{file}.{extension}", new { controller = "Public", action = "GetFileInFolder" });
routes.MapRoute("PublicContent", "{file}.{extension}", new { controller = "Public", action = "GetFile"});
现在动作方法也必须改变。
public ActionResult GetFile(string file, string extension)
{
return GetFileInFolder("", file, extension);
}
public ActionResult GetFileInFolder(string subfolder, string file, string extension)
{
var path = Path.Combine(Server.MapPath("~/Content"), subfolder, file + "." + extension);
if (!System.IO.File.Exists(path)) throw new HttpException(404, "File Not Found");
var mimetype = mimeTypes.ContainsKey(extension) ? mimeTypes[extension] : "text/plain";
return File(path, mimetype);
}
如果您开始在文件夹结构中获得多个层次,这会变得越来越丑陋。但也许这对你有用。我确定您希望项目属性中有一个复选框,但如果有的话,我不知道。