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

使用WCF Test Client调用购物车服务失败的技术求助

Troubleshooting WCF Test Client Failure with ShoppingCartService

I see you're having trouble calling methods in your ShoppingCartService using WCF Test Client. Let's break down the issues based on the code and config you provided, along with actionable fixes to get things working.

First, let's properly format your provided code for clarity:

Service1.svc.cs (Code-Behind)

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

namespace ShoppingCartService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        DigitalXDBEntities _db = new DigitalXDBEntities();

        //Fetches Images from SQL Database
        public string GetImage(object Picture)
        {
            return "data:image/jpg;base64," + Convert.ToBase64String((byte[])Picture);
        }

        //Fetches popular products
        public List<Product> GetTopProducts()
        {
            var query = (from p in _db.Products orderby p.Price select p).Take(5);
            return query.ToList();
        }

        //Fetches all DVD using subcategory product id
        public List<Product> GetDvds()
        {
            List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
            var query = (from p in _db.Products where list.Contains(p.SubCategoryID) select p);
            return query.ToList();
        }

        //Fetches all components using subcategory product id
        public List<Product> GetComponents()
        {
            IEnumerable<int> list = new List<int>() { 25, 31, 29, 30 };
            List<Product> query = (from p in _db.Products where list.Contains(p.SubCategoryID) select p).ToList();
            return query;
        }

        //Fetches all Consoles using product id
        public List<Product> GetConsoles()
        {
            IEnumerable<int> list = new List<int>() { 21, 23 };
            List<Product> query = (from p in _db.Products where list.Contains(p.SubCategoryID) select p).ToList();
            return query;
        }

        //Fetches all games using subcategory product id
        public List<Product> GetGames()
        {
            IEnumerable<int> list = new List<int>() { 9, 10, 11, 12, 14, 15 };
            List<Product> query = (from p in _db.Products where list.Contains(p.SubCategoryID) select p).ToList();
            return query;
        }

        //Fetches all handbooks using subcategory product id
        public List<Product> GetHandbooks()
        {
            IEnumerable<int> list = new List<int>() { 27, 28 };
            List<Product> query = (from p in _db.Products where list.Contains(p.SubCategoryID) select p).ToList();
            return query;
        }

        //Fetches all pc parts using subcategory product id
        public List<Product> GetPcParts()
        {
            IEnumerable<int> list = new List<int>() { 26 };
            List<Product> query = (from p in _db.Products where list.Contains(p.SubCategoryID) select p).ToList();
            return query;
        }
    }
}

IService1.cs (Service Contract)

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

namespace ShoppingCartService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        List<Product> GetDvds();
        [OperationContract]
        List<Product> GetTopProducts();
        [OperationContract]
        List<Product> GetComponents();
        [OperationContract]
        List<Product> GetGames();
        [OperationContract]
        List<Product> GetHandbooks();
        [OperationContract]
        List<Product> GetPcParts();
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
}

Web.config (Incomplete)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="

Now, let's go through the most likely causes of your failure:

1. Incomplete Web.config

Your provided Web.config cuts off mid-way in the <protocolMapping> section. This invalid XML will prevent the WCF service from initializing entirely. You need to complete this section properly. For example, a valid protocol mapping entry might look like:

<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
  <add binding="basicHttpBinding" scheme="http" />
</protocolMapping>

Also, ensure the <system.serviceModel> section is properly closed with </system.serviceModel> at the end, and the entire config has closing tags for <configuration>.

2. Missing Data Contract for the Product Class

All complex types returned by WCF services (like your Product class) need to be marked with [DataContract], and their public properties with [DataMember] to enable serialization/deserialization. Since you're returning List<Product> from all your methods, WCF can't serialize these objects without this setup.

Add the data contract attributes to your Product class:

[DataContract]
public class Product
{
    [DataMember]
    public int ProductID { get; set; }
    
    [DataMember]
    public string ProductName { get; set; }
    
    // Add [DataMember] to all properties you need to expose via the service
    [DataMember]
    public decimal Price { get; set; }
    
    [DataMember]
    public int SubCategoryID { get; set; }
    
    // Include other properties as needed
}

If Product is an Entity Framework generated class, you can either modify the T4 template to include these attributes, or create a separate Data Transfer Object (DTO) class that maps to Product and use that instead (recommended to avoid exposing EF internals).

3. Entity Framework Proxy Serialization Issues

When you return EF entities directly (like _db.Products.ToList()), EF may create proxy objects for lazy loading. These proxies can cause serialization errors in WCF because they're not marked as data contracts.

Fixes:

  • Disable lazy loading for the context when fetching data:
    _db.Configuration.LazyLoadingEnabled = false;
    var query = (from p in _db.Products orderby p.Price select p).Take(5);
    return query.ToList();
    
  • Project to a DTO (preferred): Create a ProductDTO class with only the properties you need, and map the EF Product to it using something like AutoMapper or manual mapping.

4. Enable Detailed Error Messages

Your Web.config has <serviceDebug includeExceptionDetailInFaults="false" />. Setting this to true will send detailed exception information back to the client (like WCF Test Client), which is crucial for debugging. Change it to:

<serviceDebug includeExceptionDetailInFaults="true" />

Just remember to set it back to false before deployment to avoid exposing sensitive error details.

5. GetImage Method Not Exposed in Service Contract

Your Service1 class has a GetImage method, but it's not defined in the IService1 interface with an [OperationContract] attribute. If you're trying to call this method via WCF Test Client, it won't be visible. Add it to the contract if you need to expose it:

[ServiceContract]
public interface IService1
{
    // Existing operation contracts...
    
    [OperationContract]
    string GetImage(object Picture);
}

Try addressing these issues one by one, starting with the incomplete Web.config and data contract for Product, as those are the most critical. Once you fix those, enable detailed error messages to get more insight if you still run into problems.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:23:10