为什么我不能通过AngularJS的POST向我的WebApi发送帖子?

时间:2016-11-06 02:09:26

标签: javascript angularjs asp.net-mvc asp.net-web-api

我已经将“mytest.html”发送到IIS上,这个项目由WebApi + Angularjs组成,我无法向webApi索取正确的请求......我不知道为什么?

【HTML代码】

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    </head>

    <body>
       <div ng-app="A" ng-controller="Test">
           <form method='post' name='myForm'>
               <table width="100%">
                  <tr>
                      <td>Name:</td>
                      <td><input type='text' ng-model='user.name' name='myname' required/>
                               <span style='color:red' ng-show='myForm.myname.$dirty && myForm.myname.$invalid'>Name cannot be empty!</span>
                      </td>
                 </tr>

                  <tr>
                      <td>Gender:</td>
                      <td>
                        <div ng-repeat='s in sexs'>
                        <input type='radio' ng-model='user.sex' name='mysex' value='{{s}}'>
                        {{s}}
                        </div>
                      </td>
                 </tr>
                 <tr>
                       <td>Hobby:</td>
                       <td>
                       <select ng-model='user.love' name='selLove'>
                           <option ng-repeat='l in loves' value='{{l}}'>{{l}}</option>
                       </select>
                       <span style='color:red' ng-show='selChoice(myForm.selLove.$dirty);'>You cannot choose "Please choose"</span>
                        </td>
                 </tr>
             </table>
             <input type ='submit' value='Submit' ng-click='isDisable();'/>
           </form>
      </div>

    <script>

         var app = angular.module('A',[],function($httpProvider){

            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
         });


         app.controller('Test',function($scope,$http){

           $scope.user = {};

           $scope.sexs = ['M','F'];
           $scope.loves = ['Please choose','Programming','Piano','Swimming'];

           $scope.user.sex = 'M';
           $scope.user.love = 'Please choose';

           $scope.selChoice= function(isDirty){
                var isFalse = (myForm.selLove.value == 'Please choose' && isDirty);
                $scope.myForm.selLove.$invalid = isFalse;
                $scope.myForm.$invalid |= isFalse;
                return isFalse;
           };

           $scope.isDisable = function(){

                $scope.selChoice(true);

                var requestData = $.param($scope.user);
                alert(requestData);

                if($scope.myForm.$invalid){
                    alert('Invalid form');
                }
                else{
                    $http({
                        method:'POST',
                        data: requestData,
                        url:'http://localhost:60031/api',
                        success: function (data){
                            alert(JSON.stringify(data));
                        }
                    });
                }
           };
         });
    </script>

      </body>
    </html>

【WebApi代码】

 namespace AngularJSDemo.Controllers
    {
        using Models;
        using System.Web.Http;

        public class DefaultController : ApiController
        {
            [HttpPost]
            public Person GetPerson([FromBody] Person p)
            {
                return p;
            }
        }
    }

【型号代码】

 namespace AngularJSDemo.Models
    {
        public class Person
        {
            public string Name { get; set; }
            public string Sex { get; set; }
            public string Love { get; set; }
        }
    }

【注册代码】

namespace AngularJSDemo
{
    using Newtonsoft.Json.Serialization;
    using System.Net.Http.Formatting;
    using System.Web.Http;

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.Clear();

            var jsonFormatInstance = new JsonMediaTypeFormatter();
            jsonFormatInstance.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.Add(jsonFormatInstance);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional,controller="Default" }
            );

        }
    }
}

请注意,我的谷歌浏览器控制台中的错误是:

angular.js:10695 POST http://localhost:60031/api 415(不支持的媒体类型)

我也尝试过使用json,但没有帮助:(

$http({
                    method:'POST',
                    data: {p:$scope.user},
                    url:'http://localhost:60031/api/Default',
                    success: function (data){
                        alert(JSON.stringify(data));
                    }
                });

我的内容类型是:

var app = angular.module('A',[],function($httpProvider){

                $httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
             });

因为我有不同类型的端口,为了跨域,我也这样做了:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
        <add name="Access-Control-Request-Methods" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

2 个答案:

答案 0 :(得分:1)

网址错误

网址应为:http://localhost:60031/api/Default

$vehicles = Vehicle::whereHas('car', function($q) use($jenis_mobil) {
    $q->whereHas('car_class', function($q) use($jenis_mobil) {
        $q->where('name', $jenis_mobil->name);
    });
})
->whereHas('partner', function($q) use ($dari_kota) {
    $q->whereHas('kota_pool', function($q) use ($dari_kota) {
        $q->where('name', $dari_kota->name);
    });
})
->where('year', $request->tahun_mobil)
->get();

此外,最好将数据提交为JSON而不是form-urlencoded

答案 1 :(得分:0)

总而言之,我认为:

1)我们必须使用默认值并将标题设置为“application / json”,如下所示:

$http({
                    method:'POST',
                    data: $scope.user,
                    url:'http://localhost:60031/api/Default',
                    headers:{'Content-Type':'application/json'}
                }).success(function (data){
                        alert(JSON.stringify(data));
                    });

2)让我们的WebApi“CORS”(跨域),这样才是最终的答案。

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api