0

我需要创建一个 web 服务,其中客户端和服务将在 Simple Soap 中进行对话(该请求和响应将是肥皂),我尝试在网上找到一个示例示例,其中已经完成了这件事或一些代码示例,所以我可以开始,但我认为我在搜索谷歌时很糟糕,这就是为什么到目前为止找不到任何人,有人建议使用 WCF 所以得到一篇文章

http://cshaping.com/wcf/building-a-soap-response-envelope-manually-with-the-message-class/

但是我的问题再次没有解决,我尝试使用这个示例创建一个应用程序(有很多问题:()

创建了一个控制台应用程序,Program.cs 是

using System;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Runtime.Serialization;


namespace ServiceConsole
{
    public class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost serviceHost = new ServiceHost(typeof(ServiceClient), new Uri("http://localhost:2000/")))
            {
                ServiceEndpoint serviceEndpoint = new ServiceEndpoint(
                    ContractDescription.GetContract(typeof(IService)));               

                ServiceEndpoint metadataEndpoint = new ServiceEndpoint(
                    ContractDescription.GetContract(typeof(IMetadataExchange)));               

                ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (metadataBehavior == null)
                {
                    metadataBehavior = new ServiceMetadataBehavior();
                    metadataBehavior.HttpGetEnabled = true;
                    serviceHost.Description.Behaviors.Add(metadataBehavior);
                }


                serviceHost.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "http://localhost:2000/");
                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:2000/WCFService/mex");
                serviceHost.Open();

                string requestData = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><h:HeaderItem xmlns:h=\"http://tempuri.org/\">a header item</h:HeaderItem><ActivityId CorrelationId=\"090c553b-bfcc-4e4f-94cd-1b4333fe82a9\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">377a454b-b543-4c6f-b4ac-3981029b60e6</ActivityId></s:Header><s:Body><string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">a body item</string></s:Body></s:Envelope>";
                byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/WCFService/");
                request.Method = "POST";
                request.ContentType = "text/xml; charset=utf-8";
                request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
                request.ContentLength = requestDataBytes.Length;

                StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
                streamWriter.Write(requestData);
                streamWriter.Flush();
                streamWriter.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader streamReader = new StreamReader(response.GetResponseStream());
                string responseBody = streamReader.ReadToEnd();

                Console.WriteLine("Service returned the following response...");
                Console.WriteLine("");
                Console.WriteLine(responseBody);
                Console.ReadKey();
                serviceHost.Close();
            }
        }
    }
}

我使用 svcutil.exe 生成的app.config是这样的

     <?xml version="1.0" encoding="utf-8"?>
        <configuration>
          <system.serviceModel>
            <bindings>
              <basicHttpBinding>
                <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                  <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                      maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                  <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                  </security>
                </binding>
              </basicHttpBinding>
            </bindings>
            <client>
              <endpoint address="http://localhost:2000/WebService/Service.svc"
                  binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
                  contract="IService" name="BasicHttpBinding_IService" />
            </client>
          </system.serviceModel>
        </configuration>

我的 webservioce 就像(它是一个 WCF 网站,其中端口由我提供,是 2000

服务合同是

[ServiceContract]
public interface IService
{
    [OperationContract]
    Message GetMessage(Message s);
}

[ServiceBehavior]
public class Service : IService
{
    public Message GetMessage(Message message)
    {
        string body = message.GetBody<string>();
        return Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IWebService/GetMessageResponse", "body is " + body);
    }

}

而且web.config

 <system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="http://localhost:2000/WebService/Service.svc" binding="basicHttpBinding" bindingConfiguration=""
          contract="IService" >
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <timeouts closeTimeout="00:01:10" />
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" policyVersion="Policy15" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

我的问题是 405 webmethod 不是正文 谁能告诉我这是什么问题,在创建示例之前我是 WCF 新手,这是我的第二个应用程序

4

2 回答 2

0

您无需手动创建 SOAP 消息,只需使用基本的 http 绑定即可返回 SOAP。

于 2011-07-21T18:09:01.497 回答
0

当您拥有 WCF 服务时,重点是您可以定义例如字符串、int 等参数 - 您不必处理大量的 XML 和 SOAP 标头和正文。

所以基本上,你的服务合同应该是这样的:

[ServiceContract]
public interface IService
{
    [OperationContract]
    int DoSomeMathAddTowNumbers(int num1, int num2);
}

然后您的服务实现将只实现该方法,将两个数字相加并返回结果:

public class Service : IService
{
    int DoSomeMathAddTowNumbers(int num1, int num2)
    {
         return num1 + num2;  
    }
}

没有混乱Message或 XML 操作或任何东西。

想要调用您的服务的客户端将使用svcutilVisual StudioAdd Service Reference方法创建一个 WCF 客户端代理,并且它将获得一个代理类,该代理类与它连接到的服务具有相同的方法 - 您可以使用直接,简单的参数 - 例如:

ServiceClient client = new ServiceClient();
int result = client.DoSomeMathAddTwoNumbers(42, 100);

所以基本上,我认为你需要回到绘图板并再次阅读 WCF 基础知识 - 真的应该那么难!(这就是重点——它应该让服务变得简单......)

查看MSDN的 WCF 开发人员中心的初学者指南- 它包含许多非常好的视频、截屏视频、关于如何开始使用 WCF 的文章。-

您可能还想查看 DotNet Rocks 电视剧第 135 集:Keith Elder 揭秘 WCF

于 2011-07-21T18:10:58.913 回答