问题描述
我有一个旧 url,我希望将其映射到我的 ASP.Net MVC 应用程序中的路由
I have a legacy url that I wish to map to a route in my ASP.Net MVC application
e.g. http://my.domain.com/article/?action=detail&item=22
现在在路由创建中 action
有一个特殊的意义,所以我要创建这条路由?控制器是一个 RedirectController,动作是 Item.
Now in route creation action
has a special meaning so my to create this route? The controller is a RedirectController and the action is Item.
routes.MapRoute(
name: "Redirect",
url: "article",
defaults:new { controller = "redirect", action = "item"}
);
所以我的问题是查询字符串中的 action
被 defaults
中的 action
覆盖.有没有办法解决这个问题?
So my problem is that action
in the query string gets overwritten by the action
in the defaults
. Is there a way to get around this?
推荐答案
我已经成功地使用自定义 ModelBinder 破解了它.我创建了一个名为 QueryString
I have managed to crack it using a custom ModelBinder. I create a basic class called QueryString
public class QueryString
{
private readonly IDictionary<string,string> _pairs;
public QueryString()
{
_pairs = new Dictionary<string, string>();
}
public void Add(string key, string value)
{
_pairs.Add(key.ToUpper(), value);
}
public string Get(string key)
{
return _pairs[key.ToUpper()];
}
public bool Contains(string key)
{
return _pairs.ContainsKey(key.ToUpper());
}
}
然后我为此创建我的自定义活页夹:-
Then I create my custom binder for that:-
public class QueryStringModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var queryString = new QueryString();
var keys = controllerContext.HttpContext.Request.QueryString.AllKeys;
foreach (var key in keys)
{
queryString.Add(key, controllerContext.HttpContext.Request.QueryString[key]);
}
return queryString;
}
}
在我的 Global.asax 中注册:-
In my Global.asax I register it:-
ModelBinders.Binders.Add(typeof(QueryString), new QueryStringModelBinder());
现在我可以在我的 RedirectController 中使用它:-
Now I can use that in my RedirectController:-
public RedirectToRouteResult Item(QueryString queryString)
{
// user QueryString object to get what I need
// e.g. queryString.Get("action");
}
这篇关于ASP.Net 中的路由保留字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!