SharePoint: Issue with calling an asmx web service in SharePoint 2010 through jQuery
After migration a SharePoint 2007 application to SharePoint 2010 my jQuery scripts communicating with asmx web services stopped working. The error I got was a 500 Internal Server Error. The scripts looks as follows:
$.ajax({ type: "POST", url: "http://someserver/someapp/_layouts/Services/Products.asmx/GetProductByCountry", data: JSON.stringify({ countryCode: "USA" }), dataType: "json", contentType: 'application/json; charset=utf-8', context: this, success: function (data) { alert(data.d); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } });
Note: The JSON object mentioned in the script is defined in the json2.js available at http://www.json.org.
This issue can be solved by adding an appropriate <webServices> section to the SharePoint application’s web.config (in my case it’s located at C:\inetpub\wwwroot\wss\VirtualDirectories\80). So, find the global <system.web> section in your web.config and make changes so that the result would look like the following:
<system.web> <webServices> <protocols> <add name="HttpGet" /> <add name="HttpPost" /> </protocols> </webServices> ... </system.web>
However, from the security point of view such solution is not ideal as it allows external access through the HTTP-GET and HTTP-POST messaging protocols to all your XML web services. So, it’s better to specify the access protocols for each web service separately, not affecting other ones. The <location> element added to the root <configuration> element provides us with this capability. The sample below defines the protocols for accessing the web service reachable by the specified path:
<configuration> ... <location path="_layouts/Services/Products.asmx"> <system.web> <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> </system.web> </location> ... </configuration>
Note that the _layouts virtual directory is available as a subfolder of every SharePoint Web site. So if you want to limit the use of the web service by only one SharePoint Web site, specify the path like someapp/_layouts/Services/Products.asmx.
PS Here is a good article about how to create a custom web service in SharePoint 2010.