The benefit of using JSON as a lightweight data type communication in Ajax is clear that, given security concerns, ASP.net Ajax webservice using JSON should prevent JSON hijacking. So it is usually our practice to use the POST request type and set the requested Content-type to Application/json; Charset=utf-8. But the client if you are using jquery, there are three detail issues that we should be aware of:
1: If we post without any data to the server, please specify data:{} such as:
Code
1 $.ajax({
2 type: "POST",
3 url: "PageMethod.aspx/PageMethodName",
4 data: "{}",//注意这里不可省。
5 contentType: "application/json; charset=utf-8",
6 dataType: "json"
7 });
This is because content-length must be provided when post requests are in IIS, and even if no post data.content-length should be set to 0, then jquery will not automatically set headers unless the request contains post Data. And ASP.net Ajax's JSON transfer, which requires post, so we can't change the way he asks. The simple solution is to give an empty JSON object in the request. To meet the requirements of IIS, this time Content-length is 2. At this point in the server I can completely ignore this null parameter and handle the corresponding request.
2: When the post data is not empty. We should avoid setting up Requestheader in the Beforesend event.
If the example post data is empty, if jquery cannot set the header automatically, can we help him set it by hand? When the answer is
Yes, I do. At this point we were set in the Beforesend event. As shown in the code (please note: must be set to Application/json otherwise webservice
does not return JSON. This is also due to security considerations.
Code
1 $.ajax({
2 type: "POST",
3 url: "WebService.asmx/WebMethodName",
4 beforeSend: function(xhr) {
5 xhr.setRequestHeader("Content-type",
6 "application/json; charset=utf-8");
7 },
8 dataType: "json"
9 });