请求.MVC中的QueryString



在我的HomeController中,我试图使用Request获取信息。参数

        string aa = Request.QueryString["aa"];
        string bb = Request.QueryString["bb"];

所以在地址栏中,我希望是这样的:

& lt;>什么? aa = 12345, bb = 67890

我创建了一个新路由:

        routes.MapRoute(
            "Receive",
            "Receive",
            new { controller = "Home", action = "Index" }
        );

我试着这样使用它:
http://localhost: 54321/接收? aa = 12345, bb = 67890

但是我得到以下错误:

无法找到资源。

描述:HTTP 404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下网址,并确保拼写正确。

请求的URL:/Receive

我认为你的路由是愚蠢的,这就是为什么你得到一个404。请查看一些教程,特别是在这里:asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs

另外,就像@YuriyFaktorovich说的,你真的不应该使用Request。而是将它们作为参数传递给动作方法

VB示例:

Function Retrieve(ByVal aa as String, ByVal bb as String) as ActionResult

您可以通过两种方式访问查询字符串值…

  • 获取控制器初始化中的值
  • 在你的动作
  • 中使用这些值
  • 用这些变量指定路由

1 -获取控制器初始化中的值

protected override void Initialize(RequestContext requestContext) {
    // you can access and assign here what you need and it will be fired
    //  for every time he controller is initialized / call
    string aa = requestContext.HttpContext.Request.QueryString["aa"],
           bb = requestContext.HttpContext.Request.QueryString["bb"];
    base.Initialize(requestContext);
}

2 -使用你的动作

中的值
public void ActionResult Index(string aa, string bb) {
    // use the variables aa and bb, 
    //  they are the routing values for the keys aa and bb
}

3 -使用这些变量指定路由

routes.MapRoute(
    "Receive",
    "Receive/{aa}/{bb}",
    new { 
        controller = "Home", 
        action = "Index", 
        aa = UrlParameter.Optional, 
        bb = UrlParameter.Optional }
);

路由中的url使用"Receive/",不要使用Request.Querystring

你可以修改你的动作为

public ActionResult Index(string aa, string bb) {...}

ASP。. Net MVC框架将为您添加这些项。

你的HTTP 404错误是因为你的新路由很可能在错误的地方。确保新路由在默认路由之前:

routes.MapRoute(
        "Receive",
        "Receive",
        new { controller = "Home", action = "Index" }
    ); 
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

最新更新