是否有可能改变的查询字符串变量在ASP.NET MVC路径它击中控制器之前? [英] Is it possible to change the querystring variable in ASP.NET MVC path before it hits the controller?
问题描述
我在ASP.NET MVC控制器方法是这样的:
I have a controller method in ASP.NET MVC that looks like this:
public ActionResult GetAlbumPictures(int albumId)
{
var album = AlbumRepo.GetSingle(albumId);
var pictures = album.Pictures;
return View(pictures);
}
此方法的路由看起来是这样的:
The routing for this method looks like this:
routes.MapRoute(null,
"pictures"
new { controller = "Album", action = "GetAlbumPictures" });
用户将使用以下网址获得图片,由相册ID过滤:
The user will use the following URL to get the pictures, filtered by the album ID:
GET http://server/pictures?albumid=10
不过,我想改变查询参数只是专辑
而不是 ALBUMID
:
GET http://server/pictures?album=10
这将意味着在控制器方法需要修改为:
This would mean that the controller method needs to be modified to:
public ActionResult GetPictures(int album)
{
...
}
不过,这并不理想,因为现在的方法有一个参数名为专辑
,它可以被混淆为专辑
对象而不是 ID
的专辑
。
However, this is not ideal because now the method has a parameter named album
, which can be confused as an Album
object instead of the ID
of the Album
.
我的问题是,是否有配置ASP.NET MVC使其在路由,它会收到名为专辑
A查询参数的任何方式,但随后将其传递该控制器为 ALBUMID
参数?
My question is, is there any way of configuring ASP.NET MVC so that in the routing, it will receive a querystring parameter called album
, but then pass it off to the controller as the albumId
parameter?
P.S 我知道我可以在路由表中做到这一点:
P.S. I know that I can do this in the routing table:
routes.MapRoute(null,
"album/{albumId}/pictures",
new { controller = "Album", action = "GetAlbumPictures" });
但由于历史遗留问题,我要使它成为查询字符串的方法正常工作。
But due to legacy issues, I have to make it work for the querystring method as well.
推荐答案
您可以创建自定义操作过滤器属性来处理这种情况。我没有测试此具体实施,但总的想法是做这样的事情:
You can create a custom action filter attribute to handle this scenario. I haven't tested this specific implementation, but the general idea is to do something like this:
public class AlbumAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var albumId = filterContext.HttpContext.Request.QueryString["album"] as string;
filterContext.ActionParameters["albumId"] = albumId;
base.OnActionExecuting(filterContext);
}
}
然后,用[相册]属性修饰你的操作方法:
Then, decorate your action method with the [Album] attribute:
[Album]
public ActionResult GetAlbumPictures(int albumId)
{
var album = AlbumRepo.GetSingle(albumId);
var pictures = album.Pictures;
return View(pictures);
}
这篇关于是否有可能改变的查询字符串变量在ASP.NET MVC路径它击中控制器之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!