Postman POST working but AngularJS post throwing 404 - angularjs

I'm just trying to pass some basic form data through to a web-api via AngularJS $http.
here is the function that called to send data to the API:
$http({
url: "/Portal/GenerateTimeSheets",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
data: angular.toJson($scope.placementForm),
}).then(function (response) {
}), function(response) {
};
Note: if I breakpoint and copy and paste the $scope.placementForm data into postman it works completely fine, but going through a browser is throwing errors.
Here is my api:
[HttpPost]
public void GenerateTimeSheets([FromBody]PlacementModel placement)
{
Console.WriteLine("STUB");
}
and the Placement Model:
[JsonProperty(PropertyName = "candidateName")]
public string CandidateName { get; set; }
[JsonProperty(PropertyName = "clientName")]
public string ClientName { get; set; }
[JsonProperty(PropertyName = "jobTitle")]
public string JobTitle { get; set; }
[JsonProperty(PropertyName = "placementStartDate")]
public string StartDate { get; set; }
[JsonProperty(PropertyName = "placementEndDate")]
public string EndDate { get; set; }
[JsonProperty(PropertyName = "frequency")]
public string TimeSheetFrequency { get; set; }

404 Usually denotes that the url of the request is wrong, You are missing something in the url. Validate your url with the backend. Hope it helps

Related

Ajax post jSon data in Request object

I am passing a json data using jQuery to a Ajax call. I want to read this json in my Application_BeginRequest function on global.ascx for some puspose.
Where can i find this data in "Request" object.
I found that the Questystring and the Form of Request object. both are empty.
Calling ajax function as below using jQuery
Regards
Umesh
var inputData = "{'ID':'" + ID + "', 'Code':'" + Centre +"'}";
var pageURL = window.location.protocol + "//" + window.location.host +
"/webmethod.aspx/MyFunction"
$.ajax({
type: "POST",
url: pageURL,
data: inputData,
contentType: "application/json; charset=utf-8",
dataType: "json",
P.S - Assuming you want to post the json data using **jquery** to your ASPX page, Adding a sample below.
function GetEmployee()
{
var jsonObj = {"Org":0 ,"Dept":0,"Desg":0,"Grp":0,"SubGrp":0,"Loc":0,"Prv":'CanViewEmployee',"CustAttrId":0,CustAttrVal:"","Status":'1' };
$.ajax({
url: 'EmployeeSearchControl.aspx/populateJsonResult',
datatype: 'json',
data:JSON.stringify(jsonObj),
method: 'Post',
success: function (data) {
if(data != null || data != "")
{
for(var i=0;i<data.length;i++)
{
addEmployeeToGrid(data[i]);
}
}
}
})
}
public class JSONRequest
{
public long Org { get; set; }
public long Dept { get; set; }
public long Desg{ get; set; }
public long Grp { get; set; }
public long SubGrp { get; set; }
public long Loc { get; set; }
public long Cat { get; set; }
public string Prv { get; set; }
public long CustAttrId { get; set; }
public string CustAttrVal { get; set; }
public string Status { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
string ap = Request["org"];
HttpContext.Current.Request.InputStream.Position = 0;
string jsonString = "";
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest masterDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<JSONRequest>(jsonString);
}
Hope it helps. Please let me know if you require any other help.

sending byteArray in a JSON body via angularjs http request

I want to send a post request in which the body of request is a JSON included two attributes , one of them is canvas information generated with fabricjs and the second one is a byteArray of project thumbnail. the problem is that, when I send the request , I receive null in server side.
var dataURI = this.getDataUrl($rootScope.imageType, $rootScope.imageQuality);
var strImage = dataURI.replace(/^data:image\/[a-z]+;base64,/, "");
var byteArray = covertBase64ToByteArray(strImage);
var data = {
data: {
name: name,
state: canvas.fabric.toJSON(['selectable', 'name']),
zoom: canvas.zoom,
canvasWidth: width,
canvasHeight: height,
},
typeArray: byteArray
};
$http({
method: "POST",
url: _url,
data: JSON.stringify(data),
processData: false,
transformRequest: [],
contentType: 'application/json',
})
backend Code in .Net
public IHttpActionResult InsertOrUpdateUILayout(long user_Id, long layout_Id, int userLayout_Id, int? layoutType_Id, UserlayoutContentVM data)
{
// back end code here
}
public class UserlayoutContentVM
{
public object data { get; set; }
//public string base64Image { get; set; }
public byte[] typeArray{ get; set; }
}
When posting data to the backend api you need to tell the method to read the data from the request body.
This can be done with the FromBody attribute which will map the body data to the define model.
So add all properties to one model
public class UserlayoutContentVM
{
public long user_Id { get; set; }
public long layout_Id { get; set; }
public int userLayout_Id { get; set; }
public int? layoutType_Id { get; set; }
public object data { get; set; }
public byte[] typeArray{ get; set; }
}
Then make sure the client send all data in the same structure and use the FromBody attribute in the controller method to read the values
public IHttpActionResult InsertOrUpdateUILayout([FromBody]UserlayoutContentVM data){ }

Angular js posting object to web API is null

I am posting form data to webAPI and one of object has boolean value(i.e from checkbox; Deviceselected has boolean values here in code).this object returns null in my api controller.
I tried declaring Desktop and Mobile as string in controller.That did not fix as well.
What am i missing in here?
I'm able to post other data except Deviceselected
Angualrjs controller code
$scope.SendData = function (Data) {
var GetAll = new Object();
GetAll.Redirection = Data.redirection;
GetAll.Deviceselected = new Object();
GetAll.Deviceselected.Desktop = Data.devSelected.desktop;
GetAll.Deviceselected.Mobile = Data.devSelected.mobile;
GetAll.Protocol = Data.protocol;
$http({
url: "http://localhost:61352/api/Market",
dataType: 'json',
method: 'POST',
data: GetAll,
headers: {
"Content-Type": "application/json"
}
}).then(successCallback, errorCallback);
};
})
Web API code
public class SubmitData
{
public string Redirection { get; set; }
public Deviceselected deviceSelected;
public string Protocol { get; set; }
}
public class Deviceselected
{
public Boolean Desktop { get; set; }
public Boolean Mobile { get; set; }
}
[HttpPost]
public string sendData(HttpRequestMessage request,[FromBody] SubmitData marketModel)
{
return "Data Reached";
}
Apparently it works with the same logic.1)Cleared cache 2)Run API and then load HTML

Passing list of objects from Angular to Web API

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();
}
}
CORS does not allow application/json . You were okay with text/plain
You can even avoid the headers part for now. As you said It calls the API action method but data is empty. Probably jsondata is not a valid object.
Try with the following code.
$http({
method: "POST",
url: "http://localhost:60262/api/IPUpload/getDetails",
data: JSON.stringify(jsondata)
}).then(function (data) {
public bool getDetails(List<Subnets> data)
{
}
without the[HttpPost].
I would also like to see your Subnets Class and jsondata
If I remember correctly, Angular.js triggers the preflight request when you use application/json. Your web API needs to respond to the preflight request with a 200 response.
If you are writing your own API, make sure that OPTION is enabled in the web API on the http://localhost:60262/api/IPUpload/getDetails endpoint.
After you enable the OPTION HTTP method and return the 200 Angular should work as expected.
You need to enable CORS on web API front. By default angularjs supports cross domain ajax calls. But if server doesn’t allow cross domain calls it will fail.
You can enable CORS as follow:
Enable options calls on server side.
For each actual post end point you need an options end point as well, so that when browser checks CORS and send a option call it should return 200.
Also application\json is supported in cross domain ajax calls.

How to pass two different types parameters in http POST method using angularjs to Web API?

First parameter is a complex type object(JSON) and second parameter is a simple type(String).Here I am using Web API 2.
I am putting my code below.
Web API
public class UserDetailsModel
{
[Key]
[EmailAddress]
public string LoginEmail { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string DisplayPic { get; set; }
[EmailAddress]
public string AlternateEmail { get; set; }
public string Organization { get; set; }
public string Occupation { get; set; }
public string Contact { get; set; }
public DateTime DoB { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Website { get; set; }
public string Info { get; set; }
public DateTime DateOfRegister { get; set; }
//public string LoginIP { get; set; }
public int LoginFlag { get; set; }
}
public int RegisterUser(UserDetailsModel userReg, string LoginIP)
{
.
.
.
}
angularjs
var UserDetails = {
'LoginEmail': $scope.LoginEmail,
'LoginName': $scope.LoginName,
'Password': $scope.Password,
'DoB': $scope.DoB,
'Gender': $scope.Gender,
'City': $scope.City,
'State': $scope.State,
'Country': $scope.Country
};
var request = $http({
method: 'post',
url: urlBase + '/UserDetails',
params: { 'userRegJSON': UserDetails, 'LoginIP': LoginIP }
});
Here in above code, I am getting NULL in UserDetails and 192.152.101.102 in LoginIP in Web API.
var request = $http({
method: 'post',
url: urlBase + '/UserDetails',
data: { 'userRegJSON': UserDetails, 'LoginIP': LoginIP }
});
Here in above code, I am getting NULL in both parameter UserDetails and LoginIP in Web API.
Then how to pass two or more different parameter types in http POST method using angularjs.
You cannot pass 2 types in webAPI.Either you pass everything in a single type or you can do the below
var request = $http({
method: 'post',
url: urlBase + '/UserDetails?LoginIp=' + LoginIP,
data: UserDetails,
});
In the API change the signature to
public int RegisterUser([FromBody]UserDetailsModel userReg, [FromUri]string LoginIP)
{
.
.
.
}
Go throught this:
Use simple and complex types in my api method signatures
POST multiple objects from Angular controller to Web API 2
Webapi doesn't work fairly well when you wish to pass 2 parameters in a POST
method. ModelBinding in Webapi always works against a single object because it maps a model.
There a few workarounds that you can use to make this work:
Use both POST and QueryString Parameters in Conjunction
If you have both complex and simple parameters, you can pass simple parameters on the query string. Your code should actually work with:
something like this
/baseUri/UserDetails?LoginIP=LoginIP
but that's not always possible. In this example it might not be a good idea to pass a user token on the query string though.
Refer to #Ravi A's suggestions for making changes in your code.

Resources