在 ASP .NET MVC 中修改响应文件

本文关键字:修改 响应 文件 MVC ASP NET | 更新日期: 2023-09-27 18:36:50

>我有这个JS代码:

$.post("[MyRouteName]", data, callback);

我的ASP .NET应用程序中有路由:

routes.MapRoute(
                "MyRouteName",
                "myrouteurl",
                new { controller = "Foo", action = "Bar", id = "" }
            );

我记得当请求包含 JS 的文件时,我可以强制 ASP .NET MVC 将[MyRouteName]替换为myrouteurl,但我不记得我需要覆盖哪个组件。有人可以帮助我吗?

在 ASP .NET MVC 中修改响应文件

我取得了这个结果。为了实现这一点,我编写了自己的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";
});

希望这可以帮助某人!