简体   繁体   English

接收 HTTP 响应时出错 WCF

[英]An error occurred while receiving the HTTP response WCF

I have a Windows app connecting to a WCF service that uses Entity Framework and is hosted in IIS. I get this error message when I try to return result of method in WCF service to my windows app:我有一个 Windows 应用程序连接到使用实体框架并托管在 IIS 中的 WCF 服务。当我尝试将 WCF 服务中的方法结果返回到我的 windows 应用程序时,我收到此错误消息:

An error occurred while receiving the HTTP response to http://localhost/BuyAndRechargeWcfService/BuyAndRechargeService.svc.接收到 http://localhost/BuyAndRechargeWcfService/BuyAndRechargeService.svc 的 HTTP 响应时发生错误。 > This could be due to the service endpoint binding not using the HTTP protocol. > 这可能是由于服务端点绑定未使用 HTTP 协议。 This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down).这也可能是由于 HTTP 请求上下文被服务器中止(可能是由于服务关闭)。 See server logs for more details.有关详细信息,请参阅服务器日志。

Here is my web.config file of the WCF service:这是我的 WCF 服务的web.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <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" />
        <add key="DatabaseName" value="Recharge System"/>
        <add key="ServerName" value="SAA"/>
        <add key="UserId" value="sa"/>
        <add key="Password" value="**"/>
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2" />
    </system.web>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
        <directoryBrowse enabled="true" />
    </system.webServer>
    <entityFramework>
        <providers>
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
    </entityFramework>
</configuration>

Here is exe.config file in Windows app:这是exe.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <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="DatabaseName" value="Recharge System"/>
        <add key="ServerName" value="SAA"/>
        <add key="UserId" value="sa"/>
        <add key="Password" value="**"/>
        <add key="DataSourceType" value="wcf"/>
    </appSettings>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IBuyAndRechargeService" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost/BuyAndRechargeWcfService/BuyAndRechargeService.svc"
                      binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBuyAndRechargeService"
                      contract="BuyAndRechargeService.IBuyAndRechargeService" name="BasicHttpBinding_IBuyAndRechargeService" />
        </client>
    </system.serviceModel>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Here is service code:这是服务代码:

using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using EntityFarmework;
using Sedco.SelfService.Kiosk.SharedProject;

namespace BuyAndRechargeWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BuyAndRechargeService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select BuyAndRechargeService.svc or BuyAndRechargeService.svc.cs at the Solution Explorer and start debugging.
    public class BuyAndRechargeService : IBuyAndRechargeService
    {
        private readonly BuyAndRechargeSystemModel _dataBaseEntities = new BuyAndRechargeSystemModel(new DatabaseConfiguration().GetWebConfiguration());
        
        public dynamic HandleCustomer(string action, Dictionary<string, string> customerData)
        {
            dynamic result = null;
            switch (action)
            {
                case "checkExistingPhoneNumber":
                    {
                        result= CheckExistingPhoneNumber(customerData);
                        break;
                    }

                case "getCustomers":
                    {

                        result= GetCustomers();

                        break;
                    }

                case "getCustomerInformation":
                    {
                        result= GetCustomerInformation(customerData);
                        break;
                    }
                case "rechargeBalance":
                    {
                        result= RechargeBalance(customerData);
                        break;
                    }

                case "getFilteredCustomers":
                    {
                        result= GetFilteredCustomers(customerData);
                        break;
                    }
                case "deleteCustomers":
                    {
                        result= DeleteCustomers(customerData);
                        break;
                        
                    }
                case "checkIfNoCustomers":
                    {
                        result= CheckIfNoCustomers();
                        break;
                    }
                case "addCustomer":
                    {
                        result= AddCustomer(customerData);
                        break;
                    }
                case "getExpireDate":
                {
                    result= GetExpireDate(customerData);
                    break;
                }
                case "editCustomer":
                    {
                        result= EditCustomer(customerData);
                        break;
                    }
                default:
                    return false;
            }

            return result;
        }

        public dynamic HandlePackages(string action, Dictionary<string, string> packageInfo)
        {
            dynamic result = null;
            switch (action)
            {
                case "getPackagesList":
                    result = _dataBaseEntities.Packages.Where(package => package.Type.Equals(packageInfo["packageType"]))
                        .Select(package => package.Name).ToList();
                    break;
                case "addPackage":
                    try
                    {
                        Packages package = new Packages();
                        package.Name = packageInfo["packageName"];
                        package.Type = packageInfo["packageType"];
                        package.price = Int32.Parse(packageInfo["packagePrice"]);
                        _dataBaseEntities.Packages.Add(package);
                        _dataBaseEntities.SaveChanges();
                        result = true;
                    }
                    catch
                    {
                        result = false;
                    }
                    break;
                case "getPackageTypeFromName":
                    result = _dataBaseEntities.Packages.Where(package => package.Name.Equals(packageInfo["packageName"]))
                        .Select(package => package.Type).FirstOrDefault();
                    break;
                case "checkExistingPackages":
                    int packages = _dataBaseEntities.Packages.Where(package => package.Name == packageInfo["packageName"])
                        .Select(package => package.Name).Count();
                    result = packages != 0;
                    break;
            }
            return result;
        }

        private bool EditCustomer(Dictionary<string, string> customerData)
        {
            bool isEdited = false;

            Customers customer =
                _dataBaseEntities.Customers.FirstOrDefault(customerPhone =>
                    customerPhone.PhoneNumber.Equals(customerData["phoneNumber"]));
            if (customer != null)
            {
                int packageId = _dataBaseEntities.Packages.Where(package => package.Name.Equals(customerData["packageName"]))
                    .Select(package => package.ID).FirstOrDefault();
                customer.Name = customerData["editCustomerName"];
                customer.BirthDate = customerData["editCustomerBirthDate"];
                customer.PackageID = packageId;
                _dataBaseEntities.SaveChanges();
                isEdited = true;
            }
            else
            {
                isEdited = false;
            }

            return isEdited;
        }

        private DateTime GetExpireDate(Dictionary<string, string> customerData)
        {
            DateTime? expireDate = _dataBaseEntities.Customers
                .Where(customer => customer.PhoneNumber.Equals(customerData["phoneNumber"]))
                .Select(customer => customer.ExpireDate)
                .FirstOrDefault();
            return (DateTime)expireDate;
        }

        private bool AddCustomer(Dictionary<string, string> customerData)
        {
            bool result = false;

            try
            {
                Customers customer = new Customers();
                int packageId = _dataBaseEntities.Packages.Where(package => package.Name.Equals(customerData["packageName"]))
                    .Select(package => package.ID).SingleOrDefault();
                int packagePrice = _dataBaseEntities.Packages.Where(package => package.Name.Equals(customerData["packageName"]))
                    .Select(package => package.price).FirstOrDefault();
                string expireDateADateTime = DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd HH:mm:ss");
                DateTime expireDate = DateTime.ParseExact(expireDateADateTime, "yyyy-MM-dd HH:mm:ss",
                    CultureInfo.InvariantCulture);
                customer.Name = customerData["customerName"];
                customer.PhoneNumber = customerData["phoneNumber"];
                customer.BirthDate = customerData["customerBirthDate"];
                customer.PackageID = packageId;
                customer.ExpireDate = expireDate;
                customer.Balance = packagePrice;
                _dataBaseEntities.Customers.Add(customer);
                _dataBaseEntities.SaveChanges();
                result = true;
            }
            catch (DbEntityValidationException e)
            {
                e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
                    item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
                result = false;
            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }

        private bool CheckIfNoCustomers()
        {
            bool isNoCustomer = false;
            int countOfCustomers = _dataBaseEntities.Customers.Count();
            if (countOfCustomers == 0)
            {
                isNoCustomer = true;
            }
            else
            {
                isNoCustomer = false;
            }

            return isNoCustomer;
        }

        private bool DeleteCustomers(Dictionary<string, string> customerData)
        {
            bool isDeleted = true;
            bool result = false;
            List<Customers> deleteQuery = new List<Customers>();
            foreach (string phoneNumber in customerData["phoneNumber"].Split(','))
            {
                Customers customerRow =
                    _dataBaseEntities.Customers.Single(customer => customer.PhoneNumber.Equals(phoneNumber));
                deleteQuery.Add(customerRow);

                if (customerRow != null)
                {
                    isDeleted = true && isDeleted;
                }
                else
                {
                    isDeleted = false && isDeleted;
                    break;
                }
            }

            foreach (Customers delete in deleteQuery)
            {
                if (isDeleted)
                {
                    _dataBaseEntities.Customers.Remove(delete);
                    _dataBaseEntities.SaveChanges();
                    result = true;
                }
                else
                {
                    result = false;
                }
            }

            return result;
        }

        private List<Customer> GetFilteredCustomers(Dictionary<string, string> customerData)
        {
            return _dataBaseEntities.Customers
                .Where(customers =>
                    customers.Name.Contains(customerData["Search"]) ||
                    customers.PhoneNumber.Contains(customerData["Search"])).Select(customer => new Customer
                    {
                        CustomerName = customer.Name,
                        CustomerPhoneNumber = customer.PhoneNumber,
                        CustomerBirthdate = customer.BirthDate,
                        CustomerPackageName = customer.Packages.Name,
                        CustomerBalance = Convert.ToDecimal(customer.Balance)
                    }).ToList();
        }

        private string RechargeBalance(Dictionary<string, string> customerData)
        {
            Customers customerBalance = _dataBaseEntities.Customers.Single(customerPhoneNumber =>
                customerPhoneNumber.PhoneNumber.Equals(customerData["PhoneNumber"]));
            customerBalance.Balance = customerBalance.Balance + Convert.ToDecimal(customerData["Amount"]);
            IFormatProvider culture = System.Globalization.CultureInfo.CurrentCulture;
            customerBalance.ExpireDate = DateTime.ParseExact(DateTime.Now.AddMonths(1).ToString("dd-MM-yyyy"),
                "dd-MM-yyyy", culture);
            _dataBaseEntities.SaveChanges();
            return customerBalance.Balance.ToString();
        }

        private Customer GetCustomerInformation(Dictionary<string, string> customerData)
        {
            return _dataBaseEntities.Customers
                .Where(customers => customers.PhoneNumber.Equals(customerData["PhoneNumber"])).Select(
                    customer => new Customer
                    {
                        CustomerName = customer.Name,
                        CustomerPhoneNumber = customer.PhoneNumber,
                        CustomerBirthdate = customer.BirthDate,
                        CustomerPackageName = customer.Packages.Name,
                        CustomerBalance = (decimal)customer.Balance
                    }).Single();
        }

        private XmlNode[] GetCustomers()
        {
            var customers = _dataBaseEntities.Customers.Select(customerInfo => new Customer
            {
                CustomerName = customerInfo.Name,
                CustomerPhoneNumber = customerInfo.PhoneNumber,
                CustomerBirthdate = customerInfo.BirthDate,
                CustomerPackageName = customerInfo.Packages.Name,
                CustomerBalance = (decimal)customerInfo.Balance
            }).ToList();

            //Convert the List<Customer> object to an XmlNode[] object
            XmlSerializer serializer = new XmlSerializer(typeof(List<Customer>));
            using (StringWriter stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, customers);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(stringWriter.ToString());
                return xmlDoc.ChildNodes.Cast<XmlNode>().ToArray();
            }
        }

        private bool CheckExistingPhoneNumber(Dictionary<string, string> customerData)
        {
            return _dataBaseEntities.Customers.Count(
                number => number.PhoneNumber == customerData["PhoneNumber"]) != 0;
        }
    }
}

When I try to debug the code I reach the return value of HandleCustomer method in WCF service and then I can't complete debugging (can't move to other statement the arrows is been disabled).当我尝试调试代码时,我到达了 WCF 服务中HandleCustomer方法的返回值,然后我无法完成调试(无法移动到其他语句,箭头已禁用)。

Please tell me if you want to provide you in any other parts of code如果您想在代码的任何其他部分提供给您,请告诉我

If possible, please check whether there is a record of 0 in the data found in the database.如果可能,请检查在数据库中查到的数据中是否有为0的记录。

When read in a program, it is converted to the corresponding enumeration type (enum), which does not define the enumeration value corresponding to 0. In this case, the conversion to an enumeration type does not throw an exception, and the value of the property remains 0 after the conversion.在程序中读取时,转换为对应的枚举类型(enum),并没有定义0对应的枚举值。此时转换为枚举类型不会抛出异常,取值转换后属性保持为 0。 But when it is returned to the WCF client, the above exception is thrown.但是返回给WCF客户端时,抛出上述异常。

The solution is to define the enumerated value corresponding to 0 in the enumerated type.解决方法是在枚举类型中定义0对应的枚举值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM