mvc中的动态路由

Mad*_*ddy 0 c# asp.net-mvc asp.net-mvc-4

最近我参加了面试,他在mvc询问动态路由.

问题是如何根据参数字符串或int动态路由某些操作方法.

例如 :

Public ActionResult Add(datatype variable)
{  
    //depending upon the Value he was asking how to redirect.
}
Run Code Online (Sandbox Code Playgroud)

Ayd*_*din 5

重定向不由路由处理,它由执行的Actions处理.

我想他的意思是,你如何创建路由规则来执行操作Foo,如果数据类型是string,你怎么执行的动作Bar,如果数据类型是int.

您使用Routing Constraints,下面我添加了所有支持的约束的屏幕截图.

这就是你如何使用它们

public class HomeController: Controller
{
    // foobar.com/home/123
    [Route("home/{id:int}")]
    public ActionResult Foo(int id)
    {
        return this.View();
    }

    // foobar.com/home/onetwothree
    [Route("home/{id:alpha}")]
    public ActionResult Bar(string id)
    {
        return this.View();
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息可以在这里找到.

支持的路由约束列表