第一次请求后,查询字符串中的 ASP.NET MVC 操作方法参数不会更改
我在控制器中有一个需要进行分页的操作方法。我在查询字符串中传递页码和页面大小参数。我遇到的问题是我发出的第一个请求为所有后续调用设置了参数。
public ActionResult GetStuff(string key, int? page, int? pageSize)
{
// do something magical
}
我的路线如下所示:
routes.MapRoute("GetStuff", "Stuff/{key}", new {controller = "Stuff", action = "GetStuff"});
当我开始调试我的应用程序时,我转到 url /Stuff/My_Stuff 并且关键参数是正确的,并且页面和页面大小都为空,正如我所期望的那样。如果我使用 url /Stuff/My_Stuff?page=2&pageSize=3 进行第二次调用,则 page 和 pageSize 的值仍然为空。如果我重新启动应用程序,并使我的第一次调用包含页面和页面大小参数,一切都会按我的预期进行,但随后在后续调用中更改这些值将保留第一次调用的值。事实上,即使我更改了我的网址,即使是我的路线一部分的关键参数也将保持相同的值。我缺少什么?
我在 Windows Server 2003 上使用 IIS 6.1。我使用无扩展路由。另外,实际代码位于 VB.Net 中,但我认为这并不重要。但为了充分披露,上述代码仅代表我的实际代码,而不是实际代码。
I have an action method in a controller that needs to do paging. I am passing a page number and pagesize parameter in the querystring. The problem I am having is that the first request I make sets the parameters for all subsequent calls.
public ActionResult GetStuff(string key, int? page, int? pageSize)
{
// do something magical
}
My route looks like this:
routes.MapRoute("GetStuff", "Stuff/{key}", new {controller = "Stuff", action = "GetStuff"});
When I start debugging my app, I go to the url /Stuff/My_Stuff and the key parameter is correct, and both page and pagesize are null as I would expect. If I make a second call with the url /Stuff/My_Stuff?page=2&pageSize=3 then the values of page and pageSize are still null. If I restart the app, and make my first call include page and pagesize parameters, everything works as I would expect, but then changing those values on subsequent calls retains the values from the first call. In fact, even the key parameter, which is part of my route will keep the same value, even if I change my Url. What am I missing?
I am using IIS 6.1 on Windows Server 2003. I am using extensionless routes. Also, the actual code is in VB.Net, but I don't think that should matter. But for full disclosure, the above code is only representative of my actual code, and not the actual code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到了同样的问题,因为我使用 DI 容器(Castle Windsor)来创建控制器。问题的出现是由于控制器类的生命周期设置,因为 Castle 中的默认生命周期策略是 Singleton(如果你问我,这是一个奇怪的默认值)。
似乎因为 Controller 实例在应用程序的生命周期中只创建一次,所以参数会停留在它们的第一个值上。
将生命周期设置为 Transient 解决了我的问题。
I had the same problem because I used a DI Container (Castle Windsor) to create my Controllers. The problem arose because of the lifetime settings of Controller classes, because the default lifetime policy in Castle is Singleton (a weird default if you ask me).
It seems that because the Controller instance is only created once in the application's lifetime, the parameters get stuck on their first values.
Setting the lifetime to Transient solved the problem in my case.