解决aps.net 2.0中ajax调用webservice的问题

在asp.net2.0中为了省事选择用ajax调用webservice,IDE中能调用,各种放到IIS上远程调用webservice失败(返回值500),查了各种资料今天终于解决了,分享下。

 
准备:
需要自己找到System.Web.Extensions.dll,System.Web.Extensions.Design.dll(.net3.5及以上的才有的dll自己在vs中或者网上找),并引入进项目。
Web.config配置文件中configuration节点下system.web节点里面加入:
<httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>

web前端示例(这里用jquery中封装的ajax):

$(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "WebService1.asmx/HelloWorld",
                data: "",
                contentType: "application/json;charset=utf-8",//这句必须要
                //dataType: "json",//这句可以不要
                success: function (msg) {
                    alert(msg);
                }
            });
        })

后台代码示例:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]//这个特性必须加
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }

OK,调用成功!

原文地址:https://www.cnblogs.com/moxianmanong/p/2730627.html