DongWei DongWei - 1 month ago 9
Javascript Question

Why cannot I send a post to my WebApi through AngularJS's POST?

I've sent "mytest.html" onto the IIS and this project is made up of WebApi+Angularjs, and I cannot get a right request to my webApi……I don't know why?

【Codes for 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>


【Codes for WebApi】

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

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


【Codes for model】

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


【Codes for Register】

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" }
);

}
}
}


Notice that the error in the console of my google chrome is:

angular.js:10695 POST http://localhost:60031/api 415 (Unsupported Media Type)




I've also tried to use json, but no help :(

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


And my Content-Type is:

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

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





Because I have different kinds of ports, so as to cross the domain, I also did this:

<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>

Answer

The URL is wrong

the URL should be : http://localhost:60031/api/Default

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

Also, it is better to submit the data as JSON not form-urlencoded