2014-01-09 56 views
0

我有一个具有以下作用的控制器的类型:必须有一个字符串值,或者是它实现IRouteConstraint

public ActionResult Post(int pId) 
    { 
     urlPostTitle = "Hello"; 
     pId=23; 
     return RedirectPermanent(Url.Action("PostRedirect", new { pId = pId, postTitle = urlPostTitle })); 
    } 

我的路线为:

routes.MapRoute("GetPostRedirect", "{pId}/{postTitle}", new { controller = "Blog", action = "PostRedirect", }, new { pId = @"^\d{1,3}$", postTitle = UrlParameter.Optional }); 

但我得到这个错误在return RedirectPermanent行:

The constraint entry 'postTitle' on the route with URL '{pId}/{postTitle}' must have a string value or be of a type which implements IRouteConstraint. 

我无法理解的原因错误为urlPostTitle是一个字符串,请帮我解决这个错误。

回答

0

看起来你有点混淆。试试这个:

routes.MapRoute(
    "GetPostRedirect", 
    "{pId}/{postTitle}", 
    new { controller = "Blog", action = "PostRedirect", postTitle = UrlParameter.Optional }, 
    new { pId = @"^\d{1,3}$" }); 

此:

new { controller = "Blog", action = "PostRedirect", postTitle = UrlParameter.Optional } 

为每个参数指定默认值,而这一点:

new { pId = @"^\d{1,3}$" } 

被指定哪些规定值的参数的约束被允许承担。

较新版本的MVC(4及更高版本)实际上使用Named Arguments以使区分更清楚。所以上面的代码会变成:

routes.MapRoute(
    name: "GetPostRedirect", 
    url: "{pId}/{postTitle}", 
    defaults: new { controller = "Blog", action = "PostRedirect", postTitle = UrlParameter.Optional }, 
    constraints: new { pId = @"^\d{1,3}$" }); 
相关问题