You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何创建含多个操作契约的WCF Rest服务?

Building a WCF REST Service from Your ICustomerService Interface

Hey there! Let's get your WCF REST service up and running smoothly. First, let's tweak your original interface to fix a couple of potential gaps, then we'll walk through the full implementation step by step.

1. Fix & Refine the Service Interface

Looking at your initial code, the UriTemplate values for GetSTOCK and GETSUPINFO are hardcoded (like /GetSTOCK/ABC), but the methods don't accept any parameters. If those segments (ABC, XYZ/ABC) are supposed to be dynamic input values, we need to update the templates to use placeholders and add matching parameters to the methods. Also, since we're using GET requests, WebGet is more semantically appropriate than WebInvoke (though WebInvoke will still work).

Here's the revised, functional interface:

using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

[ServiceContract]
public interface ICustomerService
{
    [OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json, 
            ResponseFormat = WebMessageFormat.Json, 
            UriTemplate = "/GetAllCustomer/")]
    List<CustomerDataContract> GetAllCustomer();

    // Updated to accept a dynamic stock code parameter
    [OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json, 
            ResponseFormat = WebMessageFormat.Json, 
            UriTemplate = "/GetSTOCK/{stockCode}")]
    List<CustomerDataContract> GetSTOCK(string stockCode);

    // Updated to accept dynamic supplier and info type parameters
    [OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json, 
            ResponseFormat = WebMessageFormat.Json, 
            UriTemplate = "/GETSUPINFO/{supplierId}/{infoType}")]
    List<CustomerDataContract> GETSUPINFO(string supplierId, string infoType);
}

// Don't forget your data contract definition!
[DataContract]
public class CustomerDataContract
{
    [DataMember]
    public int Id { get; set; }
    
    [DataMember]
    public string Name { get; set; }
    
    [DataMember]
    public string Email { get; set; }
    // Add any other properties your business logic requires
}

2. Implement the Service Class

Now create the concrete implementation of your interface. For demonstration, we'll return mock data—you can replace this with your actual database or business logic later:

public class CustomerService : ICustomerService
{
    public List<CustomerDataContract> GetAllCustomer()
    {
        // Replace with your real data retrieval logic
        return new List<CustomerDataContract>
        {
            new CustomerDataContract { Id = 1, Name = "John Doe", Email = "john@example.com" },
            new CustomerDataContract { Id = 2, Name = "Jane Smith", Email = "jane@example.com" }
        };
    }

    public List<CustomerDataContract> GetSTOCK(string stockCode)
    {
        // Use the stockCode parameter to filter or fetch relevant data
        return new List<CustomerDataContract>
        {
            new CustomerDataContract { Id = 3, Name = $"Stock {stockCode} Customer", Email = "stock@example.com" }
        };
    }

    public List<CustomerDataContract> GETSUPINFO(string supplierId, string infoType)
    {
        // Use supplierId and infoType to fetch targeted supplier-related data
        return new List<CustomerDataContract>
        {
            new CustomerDataContract { Id = 4, Name = $"Supplier {supplierId} - {infoType}", Email = "supplier@example.com" }
        };
    }
}

3. Configure the WCF Service

Option A: Host in IIS (web.config)

If you're hosting the service in IIS, update your web.config with these settings to enable REST behavior:

<system.serviceModel>
  <services>
    <service name="CustomerService">
      <endpoint address="" 
                binding="webHttpBinding" 
                contract="ICustomerService"
                behaviorConfiguration="webHttpBehavior"/>
    </service>
  </services>
  <behaviors>
    <endpointBehaviors>
      <behavior name="webHttpBehavior">
        <webHttp helpEnabled="true"/> <!-- Enables a helpful test/info page -->
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>

Option B: Self-Host (Console App)

If you prefer self-hosting in a console app for quick testing, use this code:

using System;
using System.ServiceModel;
using System.ServiceModel.Web;

class Program
{
    static void Main(string[] args)
    {
        using (WebServiceHost host = new WebServiceHost(typeof(CustomerService), new Uri("http://localhost:8080/CustomerService")))
        {
            host.Open();
            Console.WriteLine("Service is running at http://localhost:8080/CustomerService");
            Console.WriteLine("Press any key to stop the service...");
            Console.ReadKey();
            host.Close();
        }
    }
}

4. Test the Service

Once the service is up and running, test the endpoints using a browser, Postman, or curl:

  • Get all customers: GET http://localhost:8080/CustomerService/GetAllCustomer/
  • Get stock data: GET http://localhost:8080/CustomerService/GetSTOCK/ABC
  • Get supplier info: GET http://localhost:8080/CustomerService/GETSUPINFO/XYZ/ABC

You should receive JSON-formatted responses with the mock customer data we defined.


内容的提问来源于stack exchange,提问作者Gans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:49:28