2

我已经研究了很多关于这个话题的问题。当谈到 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/[模型名称]控制器

    [ActionName("CustomerLogin")]
    [HttpPost]
    //public HttpResponseMessage CustomerLogin(string username, string password)
    public HttpResponseMessage PostCustomerLogin(string username, string password)
    {

来自客户端的呼叫路径

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

找不到我缺少的东西。

有什么建议么?

4

1 回答 1

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";并且主要是绑定来自请求正文的数据。

有关更多详细信息,请阅读此处:路由和操作选择,您会发现参数绑定的默认设置为:

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

而且您在请求正文中发送数据,没有 url 参数usernamepassword

于 2013-06-06T17:40:49.977 回答