【问题标题】:asp.net webservices (.asmx)asp.net 网络服务 (.asmx)
【发布时间】:2017-04-19 10:55:21
【问题描述】:

内部网络服务使用soap 在HTTP 上工作。但是当我们尝试访问 Web 服务的[WebMethod] 时,事情是如何开始在带有 jquery ajax 的 URL 的基础上工作的呢? SOAP 是否仍然在 jQuery ajax 中发挥作用?如果是怎么办?如果不是为什么不呢?您可以使用下面的示例来保持简单。

下面是asmx的代码:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {          
        return "Hello World";
    }
}

【问题讨论】:

  • soap headers 如何与 jquery ajax 一起工作
  • @AndriiLitvinov 请不要使用inline code 来突出显示随机术语。
  • @CodeCaster,你能详细说明一下吗?或者也许提供指向 wiki 的链接?我认为突出显示技术内容时更容易阅读。
  • @CodeCaster,有道理,谢谢!

标签: c# ajax soap asmx


【解决方案1】:

可以使用AJAX 调用WebMethods,因为传输是HTTP。您可以在 Internet 和 SO 上找到许多示例:

jQuery AJAX call to an ASP.NET WebMethod

Calling ASP.Net WebMethod using jQuery AJAX

SOAP 是有效载荷的信封(具有一些附加功能)。是否要在WebMethod 中使用它取决于您。

以下是在 Web 应用程序项目中创建 Hello World 服务的方法:

[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";
    }
}

下面是你如何使用 jQuery 来使用它:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

<script>
    console.log($.ajax);
    $.ajax({
        type: "POST",
        url: "http://localhost:55501/WebService1.asmx/HelloWorld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response.d) {
            alert(response.d);
        }
    });
</script>

并且来自服务器的响应将是{d: "Hello World"},因为 jQuery 将添加 Accept 标头“application/json”。

您可以通过以下方式从控制台应用程序中使用它:

static void Main(string[] args)
{
    var client = new HttpClient();
    var uri = new Uri("http://localhost:55501/WebService1.asmx/HelloWorld")

    // Get xml
    var response = client.PostAsync(uri, new StringContent("")).Result;
    Console.WriteLine(response.Content.ReadAsStringAsync().Result);

    Console.WriteLine();

    // Get Json
    var response1 = client.PostAsync(uri,
        new StringContent("", Encoding.UTF8, "application/json")).Result;
    Console.WriteLine(response1.Content.ReadAsStringAsync().Result);
}

将输出:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

{"d":"Hello World"}

【讨论】:

  • 您好 Andrii,感谢您的回答,您能否举例说明一下。我知道如何用 jquery ajax 调用 webmethod。我想知道当 w 在应用程序(在 Web 应用程序或控制台应用程序中)使用 asmx 服务时,事情(soap 消息的序列化)在内部是如何工作的,以及当我们从 ajax 调用 web 方法时事情是如何自动改变的。
  • 不会自动改变。 SOAP 是基于 HTTP 的通信协议。所以客户端是另一个应用程序还是浏览器都没有关系。
  • @user7889160,我已经用示例更新了我的答案。
  • 谢谢真的帮了我。
猜你喜欢
  • 2013-02-08
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
相关资源
最近更新 更多