我注意到我的 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 总是包含第一个已注册 MapServiceRoute 的 web api 的开头。 (见下面的代码)
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 创建的。你可以找到它 here 。我所做的只是添加 TestController 和 Views/Test/Index.cshtml View 。在 View 中,我添加了上面显示的 Html.BeginForm。如果您启动应用程序并访问测试 Controller ,只需将鼠标悬停在提交按钮上(或查看 html 源代码),您就可以看到 url 错误。
有谁知道如何避免这个问题?
编辑 :
这适用于 web api 预览 4(2011 年 4 月)。
最佳答案
另一种方法是定义路由约束:
public class WcfRoutesConstraint : IRouteConstraint {
public WcfRoutesConstraint(params string[] values) {
this._values = values;
}
private string[] _values;
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection) {
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"
string value = values[parameterName].ToString();
// Return true is the list of allowed values contains
// this value.
bool match = !_values.Contains(value);
return match;
}
}
将约束分配给 MVC 路由
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { controller = new WcfRoutesConstraint(new string[] {"contact","login"}) }
);
这可以防止 MVC 接触网址“/login”和“/contact”
关于asp.net-mvc-3 - Wcf Web Api 服务路由与常规 asp.net mvc 路由冲突(Web api 预览版 4),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7225887/