我正在尝试创建一个将被许多网站/应用程序使用的Web Api。C#Web Api(非MVC)字典参数
Api将字典作为参数,因为它将是动态的。
C#方法:
[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调用方法:
请注意,我离开了的contentType: “应用/ JSON”,因为它抱怨它是包括CORS允许
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);
我试过绑定参数以及:
public class myParameters
{
public Dictionary<string,string> parameters { get; set; }
}
public Dictionary<string, string> ApiTest(myParameters parameters)
仍然没有运气。
在浏览器控制台上,我只是不停地从API接收“{}”。
我看了很多例子,但似乎没有帮助。我还是很新的C#这样的一些意见和答案的只有我上面(如ModelBinder的东西)
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:
经过几个小时的搜索之后,我决定从托管API的同一站点对API进行“本地”调用。 我当时能够放置contentType:'application/json;字符集= UTF-8' ,其曾与发送解析JSON对象后进入字典参数:-(
所以现在的contentType我继续搜索+ C#API +词典+ CORS