我已经研究了很多关于这个主题的问题。当谈到MVC3时,我并不懈怠,但对于我的生活,我无法弄清楚为什么我的MVC 4路由中的Web Api失败了。
Fiddler2显示服务器响应404(未找到)
IN App_Start / WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApiGet",
routeTemplate: "api/{domain}/{controller}",
defaults: new { action = "Get" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
config.Routes.MapHttpRoute(
name: "ApiPostWithAction",
routeTemplate: "api/{domain}/{controller}/{action}",
defaults: new { action = "Post" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
);
config.Routes.MapHttpRoute(
name: "DefaultApiPost",
routeTemplate: "api/{domain}/{controller}",
defaults: new { action = "Post" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
);
config.Routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: "api/{domain}/{controller}/{id}",
defaults: null,
constraints: new { id = new GuidConstraint() } // Only Guids
);
IN控制器/ Api / [ModelName]控制器
[ActionName("CustomerLogin")]
[HttpPost]
//public HttpResponseMessage CustomerLogin(string username, string password)
public HttpResponseMessage PostCustomerLogin(string username, string password)
{
来自客户的CALL路径
var url = "api/[client_specific_name]/Customer/CustomerLogin";
var userData = new {username:[someusername], password:[somepassword]};
var defaultSettings = {
type: 'POST',
data: userData
};
// SENT TO SERVER VIA AJAX ALONG WITH THE DATA ABOVE
找不到我错过的东西。
有什么建议吗?
答案 0 :(得分:3)
一种解决方案可能是引入一个对象:
public class AuthData
{
public string UserName { get; set; }
public string Password { get; set; }
}
然后更改方法的签名
[ActionName("CustomerLogin")]
[HttpPost]
//public HttpResponseMessage CustomerLogin(string username, string password)
public HttpResponseMessage PostCustomerLogin(AuthData data)
{
这将正确地找到url = "api/[client_specific_name]/Customer/CustomerLogin";
的方法,并且主要是绑定来自请求体的数据。
有关详细信息,请阅读:Routing and Action Selection,您将在其中找到param绑定的默认值:
您在请求正文中发送数据,没有网址参数username
和password