找不到Web Api路由

时间:2013-06-06 16:51:40

标签: asp.net-mvc asp.net-web-api asp.net-mvc-routing

我已经研究了很多关于这个主题的问题。当谈到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

找不到我错过的东西。

有什么建议吗?

1 个答案:

答案 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绑定的默认值:

  • 简单类型取自URI。
  • 复杂类型来自请求正文。

您在请求正文中发送数据,没有网址参数usernamepassword