C# WCF - 接收对 http://xxxxx/Service/ 的 HTTP 响应时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15821687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:04:37  来源:igfitidea点击:

WCF - An error occurred while receiving the HTTP response to http://xxxxx/Service/

c#wcfentity-frameworkef-code-first

提问by ledgeJumper

I am making this call in my WCF service:

我正在我的 WCF 服务中进行此调用:

public User GetStudentRecord(string userName)
    {
        try
        {
            return new DashboardFacade().GetStudentRecord(userName);
        }
        catch (Exception ex)
        {
            ServiceFault fault = new ServiceFault();
            fault.Operation = "GetStudentRecord";
            fault.Reason = "Who knows...";
            fault.Message = ex.Message;
            throw new FaultException<ServiceFault>(fault, fault.Message, new FaultCode(fault.Reason), fault.Operation);
        }
    }

DashboardFacade().GetStudentRecord(..) is defined like this:

DashboardFacade().GetStudentRecord(..) 定义如下:

public User GetStudentRecord(string userName)
{
    User user = ctx.Users.Where(x => x.ADUserName == userName).SingleOrDefault();
    return user;
}

ctx is my DbContext. I am using Entity Framework Code First. The User object looks like this:

ctx 是我的 DbContext。我首先使用实体​​框架代码。用户对象如下所示:

public class User
{
    public User()
    {
        //UserDetails = new UserDetail();
    }
    [Key]
    public Guid MasterKey { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string ADUserName { get; set; }
    public string UserType { get; set; }
    public virtual UserDetail UserDetails { get; set; }
    public Nullable<DateTime> LastModifiedDate { get; set; }
}

And finally, you probably need to see the web.config on the WCF Application:

最后,您可能需要查看 WCF 应用程序上的 web.config:

<?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <add name="NotMyDBContextDB" connectionString="[omitted]" providerName="System.Data.SqlClient"/>
        <add name="ApplicationContext" connectionString="Data Source=.;Initial Catalog=MyApp;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
      </connectionStrings>
   <system.web>
     <compilation debug="true" targetFramework="4.0"/>
   </system.web>
   <system.serviceModel>
     <behaviors>
       <serviceBehaviors>
          <behavior>
             <serviceMetadata httpGetEnabled="true"/>
             <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>

Can anyone point me to where I am going wrong here?

谁能指出我在这里出错的地方?

This is the exact error I am getting:

这是我得到的确切错误:

An error occurred while receiving the HTTP response to http://localhost:5843/MyService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception:
An existing connection was forcibly closed by the remote host

采纳答案by ledgeJumper

Found the root cause after a lot of swearing and thinking of how nice the weather is outside. I remove the virtual keyword from the UserDetails object that is inside the User object.

经过多次咒骂和思考外面的天气有多好,找到了根本原因。我从 User 对象内的 UserDetails 对象中删除了 virtual 关键字。

Now it works!

现在它起作用了!

As far as why this caused an issue, my assumptions are serialization or DbContext issues, but I will have to look more into it, not sure.

至于为什么这会导致问题,我的假设是序列化或 DbContext 问题,但我将不得不更多地研究它,不确定。

I'm going outside now.

我现在要去外面。

So for reference, if you wound up here and have no idea what is going on, among all the other things you should look at (size, timeout, etc):

因此,作为参考,如果您在这里结束并且不知道发生了什么,那么您应该查看的所有其他事项(大小、超时等):

Check to see if your object has virtual keyword on it.

回答by Priyan Perera

None of the methods worked for me. What I did was to debug the service while running from the WCF Test Client and I was able to find my issue. It was to do with the service library missing the connection string in the app.config.

没有一种方法对我有用。我所做的是在从 WCF 测试客户端运行时调试服务,我能够找到我的问题。这与服务库缺少 app.config 中的连接字符串有关。

Just posting if anyone has tried all the other methods and still unable to find the issue.

如果有人尝试了所有其他方法但仍然无法找到问题,请发布。

回答by Carolina

I had the same error.

我有同样的错误。

In my case I have a table with an int column called OEM. In the model layer I have a class (DTO) with that column represented by an Enum. There was a row in the table which value in OEM colum was not valid. When I was trying to bring all data using LINQ, there was an error that wasn't captured by VisualStudio. That error raised when WCF tried to retrieve the message.

在我的例子中,我有一个名为 OEM 的 int 列的表。在模型层中,我有一个类(DTO),该列由枚举表示。表中有一行 OEM 列中的值无效。当我尝试使用 LINQ 获取所有数据时,出现了 VisualStudio 未捕获的错误。当 WCF 尝试检索消息时引发该错误。

回答by TheLogicMan

I had this problem and in my case, the issue was the WCF service was returning a class that had a property with only a getter and no setter. I was trying to prevent the property from being modified by the receiver. To get around this, see this...

我遇到了这个问题,就我而言,问题是 WCF 服务返回了一个类,该类的属性只有一个 getter 而没有 setter。我试图阻止接收者修改该属性。要解决这个问题,请看这个...

WCF Services and Object Constructors

WCF 服务和对象构造函数

回答by Tim Bijnens

I had the same Exception but none of the answers above gave me a solution. I figured out the error by defining a trace in web.config :

我有同样的异常,但上面的答案都没有给我一个解决方案。我通过在 web.config 中定义跟踪来找出错误:

<system.diagnostics>
<sources>
  <source propagateActivity="true" name="System.ServiceModel" switchValue="Information, ActivityTracing">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener" name="Default">
        <filter type="" />
      </add>
      <add initializeData="C:/temp/tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="traceListener">
        <filter type="" />
      </add>
    </listeners>
  </source>
</sources>
</system.diagnostics>

I ran the website locally, fired a few failing calls and the opened the tracelog selecting the failed entry, inside that entry I saw this exception :

我在本地运行网站,触发了一些失败的调用,并打开了选择失败条目的跟踪日志,在该条目中我看到了这个异常:

The entity or complex type 'Person' cannot be constructed in a LINQ to Entities query.

无法在 LINQ to Entities 查询中构造实体或复杂类型“Person”。

Constructing the person outside of the query fixed the issue so instead of :

在查询之外构建人员解决了问题,而不是:

 var persons = (from p in db.Persons
                  select new Person
                  {
                      Id = p.Id,
                      Name = p.Name,
                      LastName = p.LastName,
                      Email = p.Email
                  }
              ).AsEnumerable();

  return persons;

I had to do :

我必须做 :

var persons = (from p in db.Persons
                  select new 
                  {
                      Id = p.Id,
                      Name = p.Name,
                      LastName = p.LastName,
                      Email = p.Email
                  }
              ).AsEnumerable()
                //construct the complex type outside of DB  (to prevent the exception that model cannot be constructed in linq to entities)
                .Select(item =>

                    new Person
                    {
                        Id = item.Id,
                        Name = item.Name,
                        LastName = item.LastName,
                        Email = item.Email
                    }).ToList(); 

            return persons;

I could have saved alot of time if the exception message was more comprehensive, judging by all the different causes outlined in this topic I guess people will agree with me.

如果异常消息更全面,我本可以节省大量时间,从本主题中概述的所有不同原因来看,我想人们会同意我的看法。

Anyway, this is how I figured out the issue, hopefully this will help someone else to

无论如何,这就是我解决问题的方式,希望这会帮助其他人

回答by Xtremexploit

Maybe you need to disable lazyloading and proxycreation, like this:

也许您需要禁用延迟加载和代理创建,如下所示:

  db.LazyLoadingEnabled = false;
  db.ProxyCreationEnabled = false;

Doing this your wcf service should work.

这样做你的 wcf 服务应该可以工作。