我有一个网站,我们最近做了一些更改,这似乎打破了我的一些路由。
最初的问题是我在使用以下表格时不允许使用405动词。
using (@Html.BeginForm("Index", "Recommendations", FormMethod.Post))
{
<button class="btn btn-large btn-primary" d="btnNext">@ViewBag.TextDisplay</button>
}
这是构建一个URL,使得它在html中显示为Recommendations/
,使Index退出(可能是因为它是默认参数。但是索引方法签名已更改,因此它采用了可选参数,这似乎导致了这个问题。
[HttpPost]
public async Task<ActionResult> Index(int? enquiryId)
要解决此问题,我将以下内容添加到我的route.config文件
中 routes.MapRoute(
name: "DefaultWithIndex",
url: "Recommendations/{enquiryId}",
defaults: new { controller = "Recommendations", action = "Index", enquiryId= UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
但现在这已经产生了拦截对RecommendationsController中其他方法的任何调用,并将我重定向回索引页面的副作用,即Recommendations/index
那么如何更改我的路由配置,以便
recommendations/
和recommendations/enquiryId=1
映射到recommendations/index
但Recommendations/<other method>
转到Recommendations/<other method>
?
答案 0 :(得分:1)
我认为enquiryId是一个int吗?如果是这样,您可以将路由限制为仅查找整数。
routes.MapRoute(
name: "DefaultWithIndex",
url: "Recommendations/{enquiryId}",
defaults: new { controller = "Recommendations", action = "Index", enquiryId= UrlParameter.Optional },
constraints: new {enquiryId= @"\d+" }); //restrict enquiryId to one or more integers
这将匹配/ Recommendations / 123但不匹配/ Recommendations / MyCustomAction
默认路由是贪婪的,并会尝试匹配所有可能的值,然后再进入下一个。