【问题标题】:ASP.NET MVC URl Routing: How to deal with ?Action=Test parameterASP.NET MVC URl 路由:如何处理 ?Action=Test 参数
【发布时间】:2011-01-08 14:22:38
【问题描述】:

我需要为一个简单游戏的在线竞赛实现一个简单的 web 应用程序。 我需要处理一个 Get 请求并做出响应。

我想,让我们只使用一个裸露的 ASP.Net MVC 应用程序,让它处理 URL。

问题是,我需要处理的网址是:

 http://myDomain.com/bot/?Action=DoThis&Foo=Bar

我试过了:

public ActionResult Index(string Action, string Foo)
    {
        if (Action == "DoThis")
        {
            return Content("Done");
        }
        else
        {
            return Content(Action);
        }
    }

问题是,字符串 Action 总是被设置为路由的动作名称。 我总是得到:

Action == "Index"

看起来 ASP.Net MVC 覆盖了 Action 参数输入,并使用了实际的 ASP.Net MVC Action。

由于我无法更改需要处理的 URL 格式:有没有办法正确检索参数?

【问题讨论】:

    标签: c# asp.net-mvc url parameters


    【解决方案1】:

    也许编写一个重命名操作查询字符串参数的 HttpModule。 HttpModules 在 MVC 获取请求之前运行。

    这是一个快速而丑陋的例子。丑,因为我不喜欢我替换参数名称的方式,但你明白了。

    public class SeoModule : IHttpModule
    {
        public void Dispose()
        { }
    
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
        }
    
        private void OnBeginRequest(object source, EventArgs e)
        {
            var application = (HttpApplication)source;
            HttpContext context = application.Context;
    
            if (context.Request.Url.Query.ToLower().Contains("action=")) {
                context.RewritePath(context.Request.Url.ToString().Replace("action=", "actionx="));
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      从 QueryString 中获取操作,这是老派的方式:

       string Action = Request.QueryString["Action"];
      

      然后你可以在它上面运行一个 case/if 语句

      public ActionResult Index(string Foo)
      {
          string Action = Request.QueryString["Action"];
          if (Action == "DoThis")
          {
              return Content("Done");
          }
          else
          {
              return Content(Action);
          }
      }
      

      这是一个额外的行,但它是一个非常简单的解决方案,开销很小。

      【讨论】:

        【解决方案3】:

        我也看到了这个SO question。它可能适用于我不知道的操作。

        【讨论】:

          【解决方案4】:

          使用普通的旧 ASP.Net 怎么样? ASP.NET MVC 对您的情况没有帮助。它实际上是在你的方式。

          【讨论】:

            猜你喜欢
            • 2011-11-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-29
            • 2011-08-06
            • 1970-01-01
            • 2010-11-22
            相关资源
            最近更新 更多