0

我正在尝试为我的 RESTful Web 服务创建 ac# 客户端应用程序。

我已将 Web 引用 ( ServiceReference1) 添加到客户端应用程序,但出现错误,例如“UserService1.svc”的端点配置不存在。

我知道“添加服务引用”在使用 Rest 服务时不会创建所有必需的配置,但我真的看不出哪里出错了!

这是我的文件

客户端应用

namespace WebServiceClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        UserService1Client webService;
        List<User> userList = new List<User>();

        public MainWindow()
        {
            InitializeComponent();            
            webService = new UserService1Client();
            serviceMethods();
        }

        private void serviceMethods()
        {
            string[] results = webService.GetUsersNames();
        }
    }
}

客户 -web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IUserService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:53215/UserService1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IUserService1" contract="ServiceReference1.IUserService1"
        name="BasicHttpBinding_IUserService1" />
    </client>

  </system.serviceModel>

</configuration>

服务 - Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>    
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
    </compilation>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfRestSample.UserService1">
        <endpoint address="" contract="WcfRestSample.IUserService1" binding="webHttpBinding" behaviorConfiguration="restBehavior"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <connectionStrings>
      <add name="cs4_databaseEntities" connectionString="metadata=res://*/cs4_model.csdl|res://*/cs4_model.ssdl|res://*/cs4_model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\cs4_database.mdf;integrated security=True;user instance=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

用户服务.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfRestSample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IUserService1" in both code and config file together.
    [ServiceContract]
    public interface IUserService1
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Xml)]
        List<string> GetUsersNames();
    }
}

用户服务1.svc

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfRestSample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "UserService1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select UserService1.svc or UserService1.svc.cs at the Solution Explorer and start debugging.
    public class UserService1 : IUserService1
    {
        public List<string> GetUsersNames()
        {
            using (cs4_databaseEntities entities = new cs4_databaseEntities())
            {
                return entities.Users.Select(user => user.Name).ToList();
            }
        }
    }
}

希望有人可以在这里帮助我!

4

1 回答 1

1

首先,对于 RESTFUL 服务,您需要声明一个 webhttpbinding,而不是 basichttpbinding(这是针对 SOAP 服务的)。在您的 REST 服务中,您应该有这些配置

1)声明您的服务及其端点

<services>
    <service name="SparqlService.SparqlService" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="SparqlService.ISparqlService" behaviorConfiguration="webHttp" />
    </service>
</services>

服务名称将为 [项目名称]。[服务名称] 行为配置将与您在下一步中声明的行为名称相同。绑定必须是 webHttpBinding,因为您希望它为 REST。如果您想要 SOAP,则声明为 basicHttpBinding 合同是 [项目名称]。[接口名称] 端点中的行为配置将是您在下一步中声明的名称

2)声明服务行为(通常默认)

<behavior name="ServiceBehavior">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="false" />
</behavior>

行为名称可以是任何名称,但它将用于匹配您在步骤 1 中声明的 BehaviorConfiguration 保留其余部分

3) Delcare 你的端点行为

<endpointBehaviors>
    <behavior name="webHttp">
        <webHttp />
    </behavior>
</endpointBehaviors>

行为名称可以是任何名称,但它将用于匹配端点中的行为配置。

最后,对于一个简单的 REST 服务,web.config 应该是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <services>
            <service name="SparqlService.SparqlService" behaviorConfiguration="ServiceBehavior">
                <endpoint binding="webHttpBinding" contract="SparqlService.ISparqlService" behaviorConfiguration="webHttp" />
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
                <behavior>
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true" />
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="webHttp">
                    <webHttp />
                </behavior>
            </endpointBehaviors>
        </behaviors>
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
</configuration>

完成 web.config 后,这是一个示例 WCF REST 服务及其各自的 C# 客户端

为了通过 POST 或 PUT 发送数据,您需要根据 WCF 服务正确构造数据。这基本上是您需要的(只需将您的应用程序的 POST 更改为 PUT)

1)WCF服务接口

[OperationContract]
[WebInvoke(Method = "POST",
    UriTemplate = "GetData",
    RequestFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.Bare)]
string GetData(DataRequest parameter);

2)WCF服务实现

public string GetData(DataRequest parameter)
{
    //Do stuff
    return "your data here";
}

3) WCF 服务中的数据协定(在本例中为 DataRequest)

[DataContract(Namespace = "YourNamespaceHere")]
public class DataRequest
{
    [DataMember]
    public string ID{ get; set; }
    [DataMember]
    public string Data{ get; set; }
}

4) 发送数据的客户端必须正确构造数据!(本例中为 C# 控制台应用程序)

static void Main(string[] args)
{
    ASCIIEncoding encoding = new ASCIIEncoding();
    string SampleXml = "<DataRequest xmlns=\"YourNamespaceHere\">" +
                                    "<ID>" +
                                    yourIDVariable +
                                    "</ID>" +
                                    "<Data>" +
                                    yourDataVariable +
                                    "</Data>" +
                                "</DataRequest>";

    string postData = SampleXml.ToString();
    byte[] data = encoding.GetBytes(postData);

    string url = "http://localhost:62810/MyService.svc/GetData";

    string strResult = string.Empty;

    // declare httpwebrequet wrt url defined above
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    // set method as post
    webrequest.Method = "POST";
    // set content type
    webrequest.ContentType = "application/xml";
    // set content length
    webrequest.ContentLength = data.Length;
    // get stream data out of webrequest object
    Stream newStream = webrequest.GetRequestStream();
    newStream.Write(data, 0, data.Length);
    newStream.Close();

    //Gets the response
    WebResponse response = webrequest.GetResponse();
    //Writes the Response
    Stream responseStream = response.GetResponseStream();

    StreamReader sr = new StreamReader(responseStream);
    string s = sr.ReadToEnd();

    return s;
}
于 2013-11-14T18:36:01.550 回答