我注意到我的 mvc 应用程序在使用时创建了错误的 url:
@using (Html.BeginForm("Test", "Test"))
{
<input type="submit" value="Submit" />
}
这是生成的 html 源代码:
<form action="/books?action=Test&controller=Test" method="post">
请注意,动作以/books开头。这是错误的!
我注意到的是 Html.BeginForm 总是包含第一个 Web api 的开头,该 web api 已向 MapServiceRoute 注册。(见下面的代码)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var builder = HttpHostConfiguration.Create();
routes.MapServiceRoute<BooksService>("books", builder);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
我花了很长时间试图弄清楚为什么我的应用程序中的 url 被破坏了,但是却一无所获。然后我决定用一个极其简单的 mvc 应用程序进行测试,果然问题可以很容易地重现。我测试过的 mvc 应用程序非常简单,它是由一个 asp mvp 创建的。你可以在这里找到它。我所做的只是添加 TestController 和 Views/Test/Index.cshtml 视图。在视图中,我添加了上面显示的 Html.BeginForm。如果您启动应用程序并访问测试控制器,只需将鼠标悬停在提交按钮上(或查看 html 源代码),您就会看到 url 是错误的。
有谁知道如何避免这个问题?
编辑:这适用于 web api preview 4(2011 年 4 月)。