具有可为 Null 类型的查询字符串路由
我正在经历那些编码员的阻塞日之一。我应该知道这一点,但我会寻求一些帮助。我有两条路线:
/Login
/Login?wa=wsignin1.0&wtrealm=http://localhost/MyApp
使用 HTTP GET 访问第一个路线的 Action 方法会返回登录页面,而第二个路线则执行一些联合身份验证操作。我定义了两个控制器方法:
public ActionResult Index();
public ActionResult Index(string wa);
路由当然不喜欢这样,因为可为空的类型使其不明确。如果路由数据中存在该值,如何对其施加约束以仅执行第二种方法?
编辑:我已经使用操作方法选择器暂时解决了该问题。这是最好的方法吗?
public class QueryStringAttribute : ActionMethodSelectorAttribute
{
public ICollection<string> Keys { get; private set; }
public QueryStringAttribute(params string[] keys)
{
this.Keys = new ReadOnlyCollection<string>(keys);
}
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
var requestKeys = controllerContext.HttpContext.Request.QueryString.AllKeys;
var result = Keys.Except(requestKeys, StringComparer.OrdinalIgnoreCase).Count() == 0;
return result;
}
}
I am having one of those coder's block days. I should know this but instead I'll ask for a little help. I have two routes:
/Login
/Login?wa=wsignin1.0&wtrealm=http://localhost/MyApp
Accessing the Action method for the first with an HTTP GET returns the login page where-as the second does some federated authentication stuff. I defined two controller methods:
public ActionResult Index();
public ActionResult Index(string wa);
The routing of course doesn't like that because the nullable type makes it ambiguous. How do I put a constraint on it to say only execute the second method if the value exists in the route data?
EDIT: I've temporarily solved the issue with an action method selector. Is this the best approach?
public class QueryStringAttribute : ActionMethodSelectorAttribute
{
public ICollection<string> Keys { get; private set; }
public QueryStringAttribute(params string[] keys)
{
this.Keys = new ReadOnlyCollection<string>(keys);
}
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
var requestKeys = controllerContext.HttpContext.Request.QueryString.AllKeys;
var result = Keys.Except(requestKeys, StringComparer.OrdinalIgnoreCase).Count() == 0;
return result;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我过去多次遇到过这个问题,我认为这是一个经典的路由问题。我所做的是:
在控制器中创建操作:
在路由定义中执行您需要执行的任何映射
I have come across this problem many times in the past and I think this is a classic routing problem. What I have done is this:
Create your actions in your controller:
Do whatever mapping you need to do in your routes definition