我有这个JS代码:
$.post("[MyRouteName]", data, callback);
我在ASP .NET应用程序中有路由:
routes.MapRoute(
"MyRouteName",
"myrouteurl",
new { controller = "Foo", action = "Bar", id = "" }
);
我记得当我请求包含JS的文件时,我可以强制ASP .NET MVC用[MyRouteName]
替换myrouteurl
,但我不记得我需要覆盖哪个组件。
有人可以帮我这个吗?
答案 0 :(得分:1)
我实现了这个结果。为了实现这一点,我编写了自己的HttpHandler:
public class JsRoutingHttpHandler : IHttpHandler
{
public JsRoutingHttpHandler()
{
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
var phisicalPath = context.Server.MapPath(context.Request.AppRelativeCurrentExecutionFilePath);
var file = File.ReadAllLines(phisicalPath);
var routeCatchRegex = new Regex(@"\[Route:([a-zA-Z]+)\]");
for (int index = 0; index < file.Length; index++)
{
var line = file[index];
var matches = routeCatchRegex.Matches(line);
foreach (Match match in matches)
{
var routeName = match.Groups[1];
var url = "ERROR[NO ROUTE FOUND]";
if (Resolver.RouteUrl.ContainsKey(routeName.Value))
{
url = Resolver.RouteUrl[routeName.Value];
}
line = line.Replace(match.Value, url);
}
context.Response.Output.WriteLine(line);
}
}
}
然后我在Web.config中注册了它:
<system.webServer>
<handlers>
<add verb="*" path="*.js" resourceType="File" name="JsRoutingHandler" type="AAYW.Core.Web.HttpHandler.JsRoutingHttpHandler"/>
</handlers>
</system.webServer>
然后我测试了它并达到了我想要的效果: 我有的文件:
$(window).load(function () {
var a = "[Route:SaveEntity]";
});
我得到的文件:
$(window).load(function () {
var a = "admin/entity/save";
});
希望这可以帮助别人!