鉴于使用Javascript调用Web Service配置略麻烦,所以记录一下。
1. 新建一个Web服务(WebService.asmx)
2. 取消注释
// [System.Web.Script.Services.ScriptService]
3. 在public string HelloWorld()方法前加上
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
并且需要
using System.Web.Script.Services;
4. 在web.config中加入
<system.web>
<webServices>
<protocols>
<add name="HttpSoap" />
<add name="HttpPost" />
<add name="HttpGet" />
<add name="Documentation" />
</protocols>
</webServices>
</system.web>
完整代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.IO; using System.Web.Script.Services; namespace WebService { /// <summary> /// WebService 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string HelloWorld() { try { return "Hello World"; } catch (Exception e) { File.WriteAllText(e.Message + "\r\n" + e.StackTrace, "log.txt"); throw; } } } }
客户端调用代码:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta name="generator" content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" /> <title>AJAX</title> <script src="jquery-2.0.3.min.js" type="text/javascript"> </script> <script> function ajax() { $.ajax({ type: "post", contentType: "application/json", url: "http://localhost/webservice.asmx/HelloWorld", success: function(msg) { alert(JSON.stringify(msg)); } }); } </script> </head> <body> <form> <input id="btn" type="button" onclick="ajax()" value="click" /> </form> </body> </html>