AngularJS 1.5.9:$http.get可传参调用Web API,$http.post无法实现
解决AngularJS 1.5.9中$http.post无法传递参数的问题
我之前也碰到过一模一样的问题,核心原因是GET和POST请求的参数传递逻辑完全不同,你现在的代码是把POST当成GET来用了,下面一步步给你捋清楚解决办法:
1. 先搞懂为什么GET可行,POST不行
你的apiGet方法是把参数放到params里,这会把参数拼接到URL的查询字符串中(比如api/order/create?order=xxx),Web API的模型绑定可以直接从URL里读取这些参数。但POST请求默认是把数据放到请求体里,如果你还是用params传参,后端根本不会从请求体里找数据,自然拿不到参数。
2. 先实现对应的apiPost方法
在你的App.js里添加和apiGet对应的POST方法,注意这里直接把数据传给$http.post的第二个参数(请求体):
self.apiPost = function (uri, data, success, failure, always) { self.isLoading = true; $http.post(uri, data) .then(function (response) { success(response); }, function (error) { failure ? failure(error) : self.handleError(error); }) .finally(function () { self.isLoading = false; always ? always() : null; }); };
3. 修改前端调用逻辑
不需要手动JSON.stringify,AngularJS的$http会自动把对象序列化为JSON,并设置正确的Content-Type: application/json请求头。直接把order对象传给apiPost即可:
$scope.placeOrder = function () { var order = { AccountId: accountId, Amount: $scope.subTotal, Tax: $scope.tax, Shipping: $scope.shipping }; // 替换apiGet为apiPost,直接传order对象 viewModelHelper.apiPost('api/order/create', order, function (result) { var orderId = result.data; }); };
4. 确保Web API后端正确接收参数
后端的Action需要明确从请求体中获取数据,用[FromBody]标记参数,同时要定义对应的模型类:
后端模型类(C#示例)
public class OrderModel { public int AccountId { get; set; } public decimal Amount { get; set; } public decimal Tax { get; set; } public decimal Shipping { get; set; } }
Web API Action
[HttpPost] [Route("api/order/create")] public IHttpActionResult CreateOrder([FromBody] OrderModel order) { // 这里就能拿到完整的order对象了 var orderId = // 你的订单创建逻辑 return Ok(orderId); }
5. 额外注意:属性名大小写匹配
AngularJS默认会把对象的属性序列化为驼峰式(camelCase),比如accountId,而C#模型默认是帕斯卡式(PascalCase),比如AccountId。为了让自动映射生效,你可以在Web API全局配置中开启驼峰序列化:
// 在WebApiConfig.cs的Register方法里添加 config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
这样前端的accountId会自动映射到后端的AccountId,不需要手动写[JsonProperty]标记。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

