At present, their work and WEBAPI related, unavoidable incoming, receive parameters. The old way is to get JSON from the request stream, and then deserialize, there are 2 uncontrollable places, one is a stream, one is deserialization, all need to try, always feel very uncomfortable. Therefore, we have done in-depth research (DU) on Webapi.
The normal WEBAPI has three ways to receive parameters:
1. In the form of a JSON string. Gets the incoming JSON string from the requested input stream, and then deserializes it into the entity it needs. The use of Request.inputstream.
2, in the form of URL to pass in. The WEBAPI is automatically converted into the corresponding entity. Similar to the submission of form forms, such as Name=aaa&pwd=bbb&token=xxx, requires the contenttype= of the request header "application/x-www-form-urlencoded
3, in the form of a JSON string, Webapi automatically converted to the corresponding entity. Contenttype= "Application/json" is required for the request header
Start with the simplest string. Crawl through the pits.
Web-side
Public class Valuescontroller:apicontroller { [httppost] publicstring GetData (string name) { return " I love " + name; } }
HTML-side JS
$ (' #btn '). Click (function () { $.ajax ({ type: "Post", URL: "Http://localhost:7601/api/values/GetData", data: "Liu Yifei", success:function (r) { alert (r); } ); });
The result met the first pit .
Conclusion: Http://localhost:7601/api/values/GetData and Http://localhost:7601/api/values/GetData?name= Liu Yifei are two different URLs
Modify the code in JS above
$ (' #btn '). Click (function () { $.ajax ({ type: "Post", URL: "Http://localhost:7601/api/values/GetData?"). Name= Liu Yifei ", success:function (r) { alert (r); } ); });
Get the results you want.
Webapi-Chuan-shen (I.)