Мне лично не нравится играть с httpHandlers по соображениям безопасности.Я хотел сделать то же самое, чтобы избежать необходимости поддерживать одну и ту же структуру папок дважды (в представлении и в папке скриптов).Итак, цель состоит в том, чтобы сохранить файлы .js в той же папке, что и мой файл .cshtml, и больше не иметь ошибку 404.
Решение
Чтобы достичь этой цели,Я использую собственный HtmlHelper и контроллер для вызовов javascript.
HtmlHelper
public static MvcHtmlString JScriptBlock<TModel>(
this HtmlHelper<TModel> html
)
{
// Get the physical path of the .js file we are looking for.
string path = ((System.Web.Mvc.RazorView)html.ViewContext.View).ViewPath.Replace(".cshtml", ".js");
path = HostingEnvironment.MapPath(path);
if (!File.Exists(path))
return null;
// We store the physical path in a session variable with GUID as the key
string guid = Guid.NewGuid().ToString();
HttpContext.Current.Session[guid] = path;
// Create the script block where the src points to the JScript controller. We give the GUID as parameter.
return MvcHtmlString.Create("<script src='/JScript/?id=" + guid + "'/>");
}
JScript Controller
public ActionResult Index(string id)
{
// id correspond to the guid generated by the MSRJScript helper
// We look if the physical path of the .js is available in the session variables
if(Session[id] == null)
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
// If the physical path was found, we simply send the file back to the browser.
string path = Session[id].ToString();
Session.Remove(id);
return File(path, "application/javascript");
}
После этого вам просто нужно добавить следующий код в View / PartialView
@Html.JScriptBlock()