How to pass list of object from Angular to a Web API ?
I tried it using content-type as application/json but it shows CORS preflight error.
Following is the Web API Post Method :
[HttpPost]
public bool getDetails(List<Subnets> data)
{
//Logic here
}
Following is the angular code :
$scope.save = function (jsondata) {
$http({
method: "POST",
url: "http://localhost:60262/api/IPUpload/getDetails",
data: jsondata,
headers: {
'Content-Type': 'application/json'
}
}).then(function (data) {
alert('success');
if (data.status) {
$scope.msg = "Data has been inserted ! ";
}
else {
$scope.msg = "Error : Something Wrong";
}
}, function (error) {
alert('fail');
$scope.msg = "Error : Something Wrong";
})
}
Following is the Subnet class :
public class Subnets
{
public string ID { get; set; }
public string Subnet { get; set; }
public string IPAddress { get; set; }
public string ServerName { get; set; }
public string Mac { get; set; }
public string Vmware { get; set; }
public string Usage { get; set; }
public string Owner { get; set; }
public DateTime ExpiryDate { get; set; }
public string Email { get; set; }
public string SwitchIP { get; set; }
public string SwitchPort { get; set; }
public string PortVLAN { get; set; }
public string Zone { get; set; }
public string Justification { get; set; }
public string CustomerID { get; set; }
public string Remarks { get; set; }
}
I tried using content-type as ' application/x-www-form-urlencoded; charset=UTF-8'. It calls the API action method but the parameter "data" is empty. With content-type as 'application/json', it shows CORS preflight error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:60262/api/StaticIPUpload/getDetails. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).
Thanks in advance.
Solution :
I added following piece of code in global.asax and it worked :
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
application/json, but you will need to enable CORS. See here under ASP.NET Web API.