【问题标题】:When send individual parameter, action result cannot be hit. when send object, it gets hit发送单个参数时,无法命中动作结果。发送对象时,它会被击中
【发布时间】:2015-09-21 08:59:56
【问题描述】:

我有一个应用程序由 ASP.Net WebAPI 2 和使用 angularJS 的 Web 项目组成。问题是当我用参数调用 API 时,它没有命中。当发送对象时,它会被击中。

anjularJS 代码:

带参数

$http({
    cache: false
        , method: 'POST'
        , url: 'http://localhost:51341/api/User/UpdateUser'
        , data: { userId: $scope.UsersId, fullName: $scope.name }
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});

Webapi 代码

[HttpPost]
public ApiResponse UpdateUser(int userId, string fullName)
{
    return this.Response(true, MessageTypes.Success, "User has been saved successfully.");
}

有对象

var model = { userId: $scope.UsersId, fullName: $scope.name };
$http({
    cache: false
        , method: 'POST'
        , url: 'http://localhost:51341/api/User/UpdateUser'
        , data: model
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});

webapi 代码

[HttpPost]
public ApiResponse UpdateUser(User model)
{
    return this.Response(true, MessageTypes.Success, "User has been saved successfully.");
}

用户类

public class User
{
    public int UserId { get; set; }
    public string FullName { get; set; }
    public int Age { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

当使用参数进行调用时,api 不会被命中。但是当使用 Object 进行调用时,api GETS 命中。

使用参数调用时我错过了什么?我们将不胜感激。

【问题讨论】:

    标签: angularjs asp.net-mvc-5 httprequest asp.net-web-api2


    【解决方案1】:

    来自WebApi docs

    最多允许从消息体中读取一个参数。所以 这不起作用:

    // Caution: Will not work!    
    public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
    

    我建议阅读的其他信息:

    https://damienbod.wordpress.com/2014/08/22/web-api-2-exploring-parameter-binding/ https://stackoverflow.com/a/24629106/3316654

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2015-01-24
      • 2020-11-09
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多