![](/img/trans.png)
[英]How to generate URL for the action with attribute routing in Asp.Net MVC
[英]ASP.NET MVC URl Routing: How to deal with ?Action=Test parameter
我需要為在線簡單游戲在線比賽實現一個簡單的webapp。 我需要處理一個Get請求並對此進行響應。
我以為,我們只使用一個裸露的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設置為路線的動作名稱。 我總是得到:
Action == "Index"
看起來ASP.Net MVC會覆蓋Action參數輸入,並使用實際的ASP.Net MVC Action。
由於無法更改需要處理的URL格式:有沒有辦法正確檢索參數?
從傳統的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);
}
}
這是額外的一行,但這是一個非常簡單的解決方案,幾乎沒有開銷。
也許寫一個HttpModule來重命名動作querystring參數。 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="));
}
}
}
我也看到了這個問題 。 它可能適用於我不知道的動作。
如何使用普通的舊ASP.Net? ASP.NET MVC在您的情況下無濟於事。 實際上是您的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.