从JavaScript调用asmx服务

时间:2012-02-27 10:58:44

标签: asp.net web-services .net-3.5 asmx

我有以下asmx服务

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]

    public class DinnerService : System.Web.Services.WebService
    {
        List<Dinner> dinners;
        public DinnerService()
        {
            dinners = new List<Dinner>();
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public Dinner HelloWorld()
        {
            var dinner = new Dinner { DinnerID = 1, Host = "Ahsan", RSVP = "Some People", Venue = "Lahore" };
            return dinner;
        }
}

我在webform的页面加载事件中从jQuery调用它,如下所示

    $(function () {
                $.ajax({
                    type: 'post',
                    url: 'http://localhost:1901/DinnerService.asmx/HelloWorld',
                    dataType: 'json',
                    data:{},
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        $('#res').html(data.d.DinnerID);
                        alert(data.d.Host);
                    }
                });
});

它适用于IE,但在Firefox和Chrome中它显示内部服务器错误,响应如下:

Request format is unrecognized for URL unexpectedly ending in '/HelloWorld'

这对我来说很奇怪,为什么它在一个浏览器上工作而不在其他浏览器上工作。我使用Visual Studio 2010和.NET 3.5进行服务。不是选择去特殊情况的WCF。互联网上的回复无法帮助我解决问题。到底发生了什么?

1 个答案:

答案 0 :(得分:1)

以下对web.config文件的设置将解决此问题。 请参阅follownig帖子。

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>