Web API and Entity framework - asp.net-web-api

I am working with back end written by another developer. I think he used Web API 2.0 and Entity Framework. Specifically I am having a problem with POST. Here is the code:
public CL_CASE Post([FromBody]CL_CASE value)
{......
I am testing it using Chrome's Advanced Rest Client. I am specifying a few parameters and clicking Send. The value I am getting is null. What might be causing that?
var response = $http({
method: 'POST',
withCredentials: true,
dataType: "json",
data: JSON.stringify(payload),
params: '',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Type': 'application/x-www-form-urlencoded'
},
url: url
});
payload is an object with properties that match CL_CASE.

There are a couple things you can check.
First, are the parameters you are passing in the body of the post or on the query string? The attribute [FromBody] on the value argument passed into the Post method is telling the model binder to look in the body of the HTTP request for matching parameters.
It's also important that the parameters you are passing are being specified using the correct Content-Type. Are you using a Content-Type header? If not, the expectation is probably that you are using form encoding. If that's the case, you should be specifying your parameters in the body like this:
paramName1=paramValue&paramName2=paramValue
Be sure the case of the parameter matches the case used for the matching property in the CL_CASE class too. These can be different cases and still be matched if you are using the right ContractResolver.
Another thing to be sure of is that you are in fact choosing to POST instead of GET.
Are there any other attributes on the Post method in your controller? If there are, these could be throwing off the binding.

Related

How to add Correlation Token parameter to web api request?

I'm using web api without deep understanding what it is, just knowing that each editable entity become a resource, that means has the uri, when web api provides the interpretation of PUT, POST, GET, DELETE HTTP commands to support CRUD operations. But what if for tracing/logging purpose I need to send correlation token together with e.g. GET request? Are there any recommendations and techniques to add to the HTTP request/routing "technical parameters"?
I have found something that need to be tested https://webapicorrelator.codeplex.com/ But actually I would prefer just to understand how it could work...
Or just add it to the heder using jquery ajax headers:
return $.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
url: url,
data: { ElectrodeId: electrodeId },
headers: { "X-CorrelationToken": correlationToken },
method: "POST",
dataType: "json",
success: function (data) {
}

While posting json to MVC controller method, I get "Length of string exceeds value set on maxJsonLength property."

While trying to post json object using:
$.ajax({
url: baseUrl + 'Controller/SaveBase64Image',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "imageData" : ' + imageData + '}'
});
I get the following error back from the server:
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
This error was partially answered RIGHT HERE.
My problem is that the serialized json object I am posting to a controller method gets automatically de-serialized in order to convert it to the correct object in the argument of the method.
Is there a way to override the class that handles this automatic de-serialization?
Thanks in advance!
After reading one of Cordova's articles on how to use the camera capture, they said that newer cameras have such high resolution that the base64 string is too large for the clientside javascript to send to server. They recommend another path of which I am working on right now. I will let you know when I have a solution.

How to specify dataType: 'json' in Angular.js $http.post?

I would like to specify dataType: 'json' as in conventional jQuery $.ajax.
Is this possible with Angular.js $http.post ?
You can use the HTTP Config object to set the headers:
$http({
method: 'POST',
url: 'somewhere.xyz',
headers: {
'Content-type': 'application/json'
}
})
From http://docs.angularjs.org/api/ng.$http
Transforming Requests and Responses
Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:
Request transformations:
if the data property of the request config object contains an object, serialize it into JSON format.
Response transformations:
if XSRF prefix is detected, strip it (see Security Considerations section below)
if json response is detected, deserialize it using a JSON parser
So no need to set a data type it is done automatically
I had the same problem, responseType:'json' solved the issue
You can use responseType:'json' instead of dataType:'json'
var promise = $http({
method: 'POST',
url: 'somewhere.xyz',
responseType:'json'
});
For further reference
https://docs.angularjs.org/api/ng/service/$http#methods_jsonp

sending data from angularjs to django

I am sending a POST AJAX request using Angularjs and its $http module to Django server. Here is an example:
$http({
method: 'POST',
url: '/url/',
data: 'test data'
}).
success(function(data, status, headers, config) {
doSomeStuffWhenSuccess();
});
The problem is what I get in Django. No matter what I send the data is always the key of QueryDict object and value of that is always an empty list.
<QueryDict: {u'test data': [u'']}>
I don't have a clue why. What am I missing?
I use almost default created Django application with default middlewares only. I created only a view and set an url in url config. Version of Django is 1.3. And I configured angular's $http module to always send a header containg csrf token to satisfy Django.
I resolved this with jQuery param function. I think it's more elegant solution.
$http({
method: 'POST',
url: '/url/',
data: $.param({test: data})
})
Now it works like I wanted.
I believe django thinks you are sending a urlencoded form, ex. key=value&key2=value2...
if you'd try:
$http({
method: 'POST',
url: '/url/',
data: 'test=data'
})
You should get
<QueryDict: {u'test': [u'data']}>
You can always obtain the data (raw body content) as follows:
request.body
Hope this is what you are looking for.

Setting processData to false in jQuery breaks my AJAX request

I've googled for a while now and can only find what processData: false does. I can't find anyone who has experienced this same issue.
I'm passing JSON back to the server and do not want jQuery to automatically convert the data to a query string so I'm setting processData to false. I can see the request firing if I take out processData, but as soon as I put it in I do not see any requests being made (using Firebug & Chrome dev tools).
$.ajax({
url: myUrl,
type: "POST",
data: {foo: "bar"},
processData: false,
contentType: 'application/json'
});
The request I was initially making was a bit more complex than this but I've simplified it to try to narrow down the problem but this simple piece of code does not work either (again, it does work if I comment out processData). Also, I am not seeing any JavaScript errors in the console.
Edit
For future web searchers: As lonesomeday pointed out, jQuery will not throw any errors if you supply either a JS object or an incorrectly formatted JSON string. It will simply not fire the request.
You want to pass the data as JSON. You are passing a Javascript object. JSON is a way of serializing Javascript objects to strings so that they can be passed around without compatibility issues.
You actually want to pass the JSON in a string:
$.ajax({
url: myUrl,
type: "POST",
data: '{"foo": "bar"}',
processData: false,
contentType: 'application/json'
});
Actually, processData by default assumes that data passed is an object and sends it as application/x-www-form-urlencoded.
Summing up everything said above by #lonesomeday and #vsm to send raw JSON (what is different from the form data) you need to:
$.ajax({
url: 'http://here-i.am/send-me/an/angel', // Determining far end
data: JSON.stringify({foo: "bar"}), // Obtaining proper JSON string from data object
processData: false, // Preventing default data parse behavior
contentType: "application/json" // Setting proper `ContentType` for our data
...
});
Figure I'd add my current understanding (as of a few hours..)
ProcessData = true : convert an object's name value pairs into a URL encoding, or an array's objects into name value pairs, or take a string as a literal.
ProcessData = false: take a string as a literal, or call an object's ToString() method.
On top of the ProcessData = true, by setting the 'traditional' flag, it can send it using a recursive encoding that captures complex structures, or a flat name value pair list.
So with respect to the OP, it worked without specifying processData since the default is true. So it converted the name value pairs in the object to a URLEncoded form. When you add the line back in, it calls your object's toString() method. Since you don't have a URL encoded string being returned by a toString() method (you have none), you will get a string such as "[object Object]". Perhaps jQuery cannot send strings that aren't URL encoded, or does not use the inherited toString() method.
The two solutions presented convert the object to a JSON string, and thus there is no processing, and thus processData does nothing. The contentType setting helps the server understand what is being sent.
In addition, one person commented that processing adds the encoded properties to the URL. Not quite: It sends that data via the most appropriate method; GET means appended to the URL, and POST means a urlencoded http body.

Resources