【问题标题】:Web Api Insert Works in Postman but not from code [duplicate]Web Api Insert 可以在 Postman 中工作,但不能来自代码 [重复]
【发布时间】:2018-12-17 03:56:38
【问题描述】:

以下简单的插入记录方法可以在 Postman 中使用,但我无法在我的 AngularJS 控制器中使用。

Postman Headers (Post)  
Key ContactID  Value 0  
Key FName      Value John  
Key LName      Value Smith  
Key Cache-Control Value no-cache  
Key Content-Type  Value application/x-www-form-urlencoded
$scope.insert = function () {

 var obj = { "ContactID": 0, "FName": "John", "LName": "Smith" };

 var url = "http://********************.net/api/create";

 $http({
     method: 'POST',
     url: url,
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
     dataType: 'json',
     contentType: 'application/json',
     data: obj
  });
}

【问题讨论】:

  • 你绝对需要它是x-www-form-urlencoded吗?您需要先serialise it。否则有$http.post(url, obj)就足够了
  • 我的 C# 方法 [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpPost] [System.Web.Http.Route ("api/Create")] public HttpResponseMessage Create([FromBody] Contact model) { var c = new Contact(); c.FName = 型号.FName; c.LName = 模型.LName;存储库。添加(c);返回新的 HttpResponseMessage(HttpStatusCode.OK);如果我包含 x-www-form-urlencoded 它会插入一条带有空白字段的记录。如果我排除它,则不会插入记录。
  • 编辑您的问题以包含 C# 代码并添加相关标签
  • 已解决 $http({ method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param (dataObj) });

标签: angularjs asp.net-web-api insert postman angularjs-http


【解决方案1】:

仅使用 AngularJS 服务的 URL 编码变量

使用 AngularJS 1.4 及更高版本,两个服务可以处理 POST 请求的 url 编码数据的过程,无需使用 transformRequest 或使用 jQuery 等外部依赖项来操作数据:

  1. $httpParamSerializerJQLike - 受 jQuery 的 .param() 启发的序列化程序

  2. $httpParamSerializer - Angular 自身用于 GET 请求的序列化程序

使用示例

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多