2010-01-23 90 views
1

我需要爲簡單的遊戲在線競賽實現一個簡單的webapp。 我需要處理Get請求並對此作出響應。ASP.NET MVC URl路由:如何處理?Action =測試參數

我想,讓我們只使用一個純粹的ASP.Net MVC應用程序,並讓它處理URL。

問題是,我需要處理的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 == "Index" 

它看起來像ASP.Net MVC覆蓋操作參數的輸入,並使用實際的ASP.Net MVC行動。

因爲我無法更改我需要處理的URL的格式:有沒有辦法正確檢索參數?

回答

5

抓住從查詢字符串,老同學的方式行動:

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

然後你就可以/如果它語句

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

這是一個額外的行運行的情況下,但這是一個非常簡單的解決方案,幾乎沒有開銷

+0

這是一個很好的解決方案。 – jessegavin 2010-01-23 17:37:33

+0

好,簡單,漂亮! – Peterdk 2010-01-23 17:42:12

0

也許寫一個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=")); 
     } 
    } 
} 
0

如何使用普通的舊ASP.Net? ASP.NET MVC不能幫助你的情況。這實際上是你的方式。