Reputation: 484
I am trying to create a Web Api that will be used by many websites / apps.
The Api takes dictionary as parameter as it will be dynamic.
C# Method:
[HttpPost]
public Dictionary<string, string> ApiTest(Dictionary<string, string> parameters )
{
Dictionary<string, string> dic_data = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> tmp in parameters)
{
dic_data[tmp.Key] = tmp.Value;
}
return dic_data;
}
Ajax Call to Method:
Please note i left out contentType: "application/json" as it complains about it being including with CORS allowed
var data = {"parameters":{"product_id":"1","product_model":"HFJ5G1.5","product_type":"plat","product_return":"graviteits"}};
//var data = {AlbumName: "Dirty Deeds",Songs:[ { SongName: "Problem Child"},{ SongName: "Squealer"}]};
var parameters = {};
parameters['1'] = 10;
parameters['2'] = 11;
$.ajax({
type :'POST',
url : 'http://localhost:8082/api/WebController/ApiTest/',
dataType : 'json',
data: parameters ,
success : function(data) {
console.log(data);
I have tried Binding the parameter as well:
public class myParameters
{
public Dictionary<string,string> parameters { get; set; }
}
public Dictionary<string, string> ApiTest(myParameters parameters )
Still no luck.
On the browser console, I just keep receiving back "{}" from the API.
I have looked at many examples but none seem to help. I'm still very new to C# so some of the comments and answers was just above me (like the ModelBinder stuff)
Passing List of KeyValuePair or IDictionary to Web Api Controller from Javascript
Method with Dictionary Parameter in Asp.Net Web API
WebApi bind body to Json dictionary
Deserialize JSON into dictionary in Web Api controller
UPDATE:
After a few more hours of searching, i decided to make a "local" call to the API from the same site that hosts the API. I was then able to put in place contentType: 'application/json; charset=utf-8', which had no problems with sending parsing JSON post object into Dictionary parameter :-(
So now my search continues of contentType + C# Api + Dictionary + CORS
Upvotes: 3
Views: 1519
Reputation: 484
CORS was enabled on the server. With simple binding parameters like strings it worked fine Crossdomain. Dictionary where is failed.
However i had to go one step further on IIS to enable specifying the content type in the AJAX call
jQuery CORS Content-type OPTIONS
I have tested it without IIS content type header specified , and even if i add the crossDomain: true, I still get Jquery error complaining about CORS
Upvotes: 1