Jas*_*ill 34 asp.net-mvc routing asp.net-mvc-routing
我正在尝试在MVC中设置自定义路由,以便采用以下格式从另一个系统获取URL:
../ABC/ABC01?Key=123&Group=456
第二个ABC之后的01是一个步骤编号,这将改变,键和组参数将改变.我需要将此路由路由到控制器中的一个操作,步骤编号键和组作为参数.我尝试了以下代码,但它抛出异常:
码:
routes.MapRoute(
"OpenCase",
"ABC/ABC{stepNo}?Key={key}&Group={group}",
new {controller = "ABC1", action = "OpenCase"}
);
Run Code Online (Sandbox Code Playgroud)
例外:
`The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.`
Run Code Online (Sandbox Code Playgroud)
Hec*_*rea 39
您不能在路由中包含查询字符串.试试这样的路线:
routes.MapRoute("OpenCase", "ABC/ABC{stepNo}",
new { controller = "ABC1", action = "OpenCase" });
Run Code Online (Sandbox Code Playgroud)
然后,在您的控制器上添加如下方法:
public class ABC1 : Controller
{
public ActionResult OpenCase(string stepno, string key, string group)
{
// do stuff here
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET MVC将自动将查询字符串参数映射到控制器中方法中的参数.
定义路由时,不能/
在路由的开头使用 a :
routes.MapRoute("OpenCase",
"/ABC/{controller}/{key}/{group}", // Bad. Uses a / at the beginning
new { controller = "", action = "OpenCase" },
new { key = @"\d+", group = @"\d+" }
);
routes.MapRoute("OpenCase",
"ABC/{controller}/{key}/{group}", // Good. No / at the beginning
new { controller = "", action = "OpenCase" },
new { key = @"\d+", group = @"\d+" }
);
Run Code Online (Sandbox Code Playgroud)
尝试这个:
routes.MapRoute("OpenCase",
"ABC/{controller}/{key}/{group}",
new { controller = "", action = "OpenCase" },
new { key = @"\d+", group = @"\d+" }
);
Run Code Online (Sandbox Code Playgroud)
那么您的操作应如下所示:
public ActionResult OpenCase(int key, int group)
{
//do stuff here
}
Run Code Online (Sandbox Code Playgroud)
看起来您正在将stepNo
和“ABC”放在一起以获得一个控制器ABC1
。这就是为什么我用{controller}
.
由于您还有一个定义“键”和“组”的路由,因此上述路由还将捕获您的初始 URL 并将其发送到操作。
归档时间: |
|
查看次数: |
51999 次 |
最近记录: |