WebRequest handshake fails due to unexpected packet format - asp.net

I have a number of ASP.NET websites and a webservice that use the same code to "login" to a third party website. This includes basically using a WebRequest to do a HTTP POST to the login page of the website with my credentials, storing the resulting cookie in a CookieContainer and using that CookieContainer in any following WebRequests to authorize my website to pages on the third party website.
The code is basically as follows:
public LoginResults Login()
{
// Create the webrequest
var request = CreateInitialWebRequest(LOGIN_URL);
request.AllowAutoRedirect = false;
// Set the cookiecontainer, which will be filled with the authentication cookies
this.cookieContainer = new CookieContainer();
request.CookieContainer = this.cookieContainer;
// Set the username and pw in a HTTP POST call
SetPostContent(request, string.Format(LOGIN_PARAMETERS, this.Username, this.Password));
// Read the response
using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = httpWebResponse.GetResponseStream())
{
// Omitted:
// read response and determine if login was successful
}
}
}
private HttpWebRequest CreateInitialWebRequest(string uri)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
return request;
}
private HttpWebRequest CreateWebRequest(string uri)
{
var request = this.CreateInitialWebRequest(uri);
request.CookieContainer = cookieContainer;
request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, */*";
request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";
request.Method = "GET";
request.Timeout = 10000; // 10 sec
return request;
}
private static void SetPostContent(HttpWebRequest req, string postData)
{
req.Method = "POST";
byte[] bytes = new ASCIIEncoding().GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = (long)bytes.Length;
((WebRequest)req).GetRequestStream().Write(bytes, 0, bytes.Length);
((WebRequest)req).GetRequestStream().Close();
}
This code has been working for a LONG time (months, over half a year). Since this weekend it has started failing very often (90% of the time I estimate, but not 100% of the time). The error I keep seeing is: System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
The stack-trace is as follows:
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at iRacingForumService.HttpPost.SetPostContent(HttpWebRequest req, String postData)
at iRacingForumService.HttpPost.Login()
When I google this error the only solution I keep seeing is to disable the KeepAlive property of the WebRequest and/or setting the ProtocolVersion to HttpVersion10. I tried both (in every combination possible) and nothing helps.
The error does not appear always, but when it does appear I can keep trying all I like, I will keep getting the error again and again and again. If I leave it for a few minutes and try again, I have a chance that it will work (and once it does, it will keep working for a while).
The strange part is that I did not change anything on my end; this code has been running for months without problems. It is entirely possible that the third party website changed something on their end, and/or my webhosting provider changed something. But just in case I can do something to remedy this problem I wanted to ask if I am doing something wrong.
I could contact the third party website (will probably not get a response) or my webhosting, but I'd need a better idea of what exactly is going wrong because just throwing this error to them will probably not help them.
So, is there anything I can do, or is there a good reason why I am suddenly seeing this error across all of my websites (they are all connecting to the same third party site)?
Thanks

Since this happens intermittently you might need to contact the server administrator and find out whats going on. It's possible the server simply rejects or closes off the connection due to load, misconfiguration or some other network issue.

Related

ASP.NET Sharepoint CSOM error: An existing connection was forcibly closed by the remote host

I have an ASP.NET application running under .NET Framework 4.7.2.
In my application I am trying to connect to my Sharepoint site to create or rename folders.
Unfortunately I am getting below error.
I've been searching around on the internet and found a lot of articles talking about TLS but my application has TLS 1.2 by default due to the .NET Framework 4.7.2.
Does anyone would know the reason/background of the error?
(I don't have the error on my local machine (no SSL), error only occurs after deploying to my hosting environment with SSL)
This is the full error message:
Server Error in '/' Application.
An existing connection was forcibly closed by the remote host
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +106
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +130
[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +291
System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) +32
System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +156
System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) +281
System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +49
System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) +162
System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) +542
System.Net.TlsStream.CallProcessAuthentication(Object state) +42
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) +228
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) +21
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) +64
System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result) +778
System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size) +52
System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size) +103
System.Net.ConnectStream.WriteHeaders(Boolean async) +388
[WebException: The underlying connection was closed: An unexpected error occurred on a send.]
System.Net.HttpWebRequest.GetResponse() +1399
Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute() +37
Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate() +514
Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest() +126
Microsoft.SharePoint.Client.ClientContext.ExecuteQuery() +44
Axius.Presentation.Website.frmAdminProjectDossierDetail.chkDossierSharepoint_CheckedChanged(Object sender, EventArgs e) in C:\inetpub\wwwroot\Axius.Presentation.Website\frmAdminProjectDossierDetail.aspx.cs:3637
System.Web.UI.WebControls.CheckBox.OnCheckedChanged(EventArgs e) +116
System.Web.UI.WebControls.CheckBox.RaisePostDataChangedEvent() +139
System.Web.UI.WebControls.CheckBox.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +12
System.Web.UI.Page.RaiseChangedEvents() +132
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1559
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3930.0
And this is the code:
using (ClientContext context = new ClientContext("https://mysite.sharepoint.com/"))
{
var passWord = new SecureString();
foreach (char c in "XXXXXXXXXX".ToCharArray()) passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("my#account.com", passWord);
List oList = context.Web.Lists.GetByTitle(#"Gedeelde documenten");
FolderCollection folders = oList.RootFolder.Folders;
context.Load(folders);
context.ExecuteQuery(); //this is frmAdminProjectDossierDetail.aspx.cs:3637 visible in the error
foreach (Folder folderr in folders)
{
if (folderr.Name == "01 PROJECTEN DOCS")
{
//code continues
}
}
}
There are at least two parts of a TLS connection: version and ciphersuites. You need to check the ciphers you have on your local machine:
https://learn.microsoft.com/en-us/powershell/module/tls/get-tlsciphersuite?view=windowsserver2022-ps
Then you should check the ciphers that are available on the sharepoint site:
https://www.ssllabs.com/ssltest/
At least one of the ciphers must match in order to complete the connection.

Calling an endpoint using HttpClient using Https works on one machine but not another

The code below is used in a traditional asp.net web page monolith app to call a handful of microservices hosted in an amazon ec2 instance. While developing the new services, the calls were made using http. This was prior to security hardening. Now, we are calling the remote webservices using https.
Https, works on my local machine, however, when deployed to IIS on a remote DEV server, the following errors are being returned.
Dim url = "https://microservice/api/someroute"
Dim client As New HttpClient
client.DefaultRequestHeaders.Add("ClientKey", clientKey)
client.DefaultRequestHeaders.Add("Bearer", AuthenticationJwt)
client.DefaultRequestHeaders.Add("TrackingId", trackingId)
'.Result is used because the asp.net web page lifecycle is synchronous
' and in some cases, the lifecycle has completed and there is no thread to come back to
Dim response = client.GetAsync(url).Result
Changed to using HTTPS first exception:
An error occurred while sending the request. at
System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface
SecModule, String package, CredentialUse intent, SecureCredential scc)
at
System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse
credUsage, SecureCredential& secureCredential) at
System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse
credUsage, X509Certificate2 selectedCert, Flags flags) at
System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]&
thumbPrint) at
System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32
offset, Int32 count, Byte[]& output) at
System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32
offset, Int32 count) at
System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
count, AsyncProtocolRequest asyncRequest) at
System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst,
Byte[] buffer, AsyncProtocolRequest asyncRequest) at
System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult
lazyResult) at
System.Net.TlsStream.CallProcessAuthentication(Object state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.BeginWrite(Byte[] buffer, Int32 offset, Int32
size, AsyncCallback asyncCallback, Object asyncState) at
System.Net.TlsStream.UnsafeBeginWrite(Byte[] buffer, Int32 offset,
Int32 size, AsyncCallback asyncCallback, Object asyncState) at
System.Net.PooledStream.UnsafeBeginWrite(Byte[] buffer, Int32 offset,
Int32 size, AsyncCallback callback, Object state) at
System.Net.ConnectStream.WriteHeaders(Boolean async)
Added the following code:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Exception changed to:
An error occurred while sending the request.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)

SMTP SocketException (0x2745) Error (ASP.NET)

I have a mail send script which is used to send out confirmations to users and staff when registrations occur etc. Of recent it seems we have been experiencing issues with the mail sending get very intermittent sends, and mainly erroring.
I've been working with the hoster to no avail. The exception is as follows:
[SocketException (0x2745): An established connection was aborted by the software in your host machine]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6528783
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +130
[IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +296
System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count) +45
System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count) +106
System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) +203
System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) +16
System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response) +54
System.Net.Mail.DataStopCommand.Send(SmtpConnection conn) +28
System.Net.Mail.SmtpConnection.OnClose(Object sender, EventArgs args) +8
System.Net.ClosableStream.Close() +54
System.Net.Mail.MailWriter.Close() +65
System.Net.Mail.SmtpClient.Send(MailMessage message) +1433
Now I have tried different authenticated users, different email contents and the common theme seems to be email with an attachment or emails with an HTML body seem prone to failure. My view is firmly that the mail server is the party that is disconnecting the request.
For reference I'm using asp.net 4.0 with a very standard set of code.
My hoster seems unable to locate or even resolve the issue.

"Invalid use of response filter" when rewriting ASP.NET output

I have a very basic ASP.NET response filter that works "fine." I use it to replace the domain for static resources.
My code in the controller looks like this:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
_cdnRewriter.Stream = filterContext.RequestContext.HttpContext.Response.Filter;
filterContext.RequestContext.HttpContext.Response.Filter = _cdnRewriter;
}
And the rewrite filter itself:
public override void Write(byte[] buffer, int offset, int count)
{
var html = Encoding.Default.GetString(buffer, offset, count);
//manipulate html
byte[] outData = Encoding.Default.GetBytes(html);
Stream.Write(outData, 0, outData.GetLength(0));
}
For certain pages on my site (I can't find the rhyme or reason yet), I get a "HTTP Web Exception: Invalid use of response filter" perhaps 90% of the time. Simply refreshing a dozen times will get the correct output, but refreshing again will show the exception:
[HttpException (0x80004005): Invalid use of response filter]
System.Web.HttpResponseStreamFilterSink.VerifyState() +4097234
System.Web.HttpResponseStreamFilterSink.Write(Byte[] buffer, Int32 offset, Int32 count) +28
NeoSmart.Web.CdnRewriteFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +452
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +359
System.Web.HttpResponse.FilterOutput() +121
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +119
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
Am I doing something wrong in my response filter?
I probably should have known better: response filters should not be shared. I was using an object per class, creating a new response filter each time the OnActionExecuted function was called resolved the issue.

An error occurred while receiving the HTTP response to <My wcf service deployed at IIS>

When I try to invoke my web service which is on a different server(Production) from asp.net server side web page, it gets executed without any exception sometimes and sometimes I get this exception mentioned in title. I have used wshttpbinding. I am also posting the complete stack trace. But the last inner exception says :
Unable to read data from the transport
connection: An existing connection was
forcibly closed by the remote host.
Based on my search, somewhere it says its due to wrong binding , somewhere its written IIS permissions are blocking , and also small time out limits. I have increased the time out but have not altered bindings and IIS account because I believe had that been the problem it would not have executed successfully even once. The behavior is highly sporadic with 50% success rate. And also some users have reported this issue with normal asp.net calls also where no wcf is involved.
This webservice call does not takes any parameters and does not return any data either. (FireAndForget kind of scenerio).
Exception Message:
An error occurred while receiving the
HTTP response to
https://json.clickable.com/BMS/NetSuiteCommunicationService.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.
Stack Trace:
Server stack trace: at
System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
webException, HttpWebRequest request,
HttpAbortReason abortReason) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout) at
System.ServiceModel.Channels.RequestChannel.Request(Message
message, TimeSpan timeout) at
System.ServiceModel.Channels.ClientReliableChannelBinder1.RequestClientReliableChannelBinder1.OnRequest(TRequestChannel
channel, Message message, TimeSpan
timeout, MaskingMode maskingMode) at
System.ServiceModel.Channels.ClientReliableChannelBinder1.Request(Message
message, TimeSpan timeout, MaskingMode
maskingMode) at
System.ServiceModel.Channels.ClientReliableChannelBinder1.Request(Message
message, TimeSpan timeout) at
System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message
message, TimeSpan timeout) at
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
message, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannel.Call(String
action, Boolean oneway,
ProxyOperationRuntime operation,
Object[] ins, Object[] outs, TimeSpan
timeout) at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime
operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at
Clickable.Scheduler.BLL.NetsuiteService.INetSuiteCommunicationService.ExecuteAddAdNetworkToCustomerTask()
at
Clickable.Scheduler.BLL.Configuration.Tasks.AdNetworkToCustomerTask.Run()
at
Clickable.Scheduler.BLL.Configuration.Tasks.Task.Excecute()
Exception Message: The underlying
connection was closed: An unexpected
error occurred on a receive.
Stack Trace: at
System.Net.HttpWebRequest.GetResponse()
at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout)
Exception Message: Unable to read data
from the transport connection: An
existing connection was forcibly
closed by the remote host.
Stack Trace: at
System.Net.Sockets.NetworkStream.Read(Byte[]
buffer, Int32 offset, Int32 size) at
System.Net.FixedSizeReader.ReadPacket(Byte[]
buffer, Int32 offset, Int32 count)
at
System.Net.Security._SslStream.StartFrameHeader(Byte[]
buffer, Int32 offset, Int32 count,
AsyncProtocolRequest asyncRequest)
at
System.Net.Security._SslStream.StartReading(Byte[]
buffer, Int32 offset, Int32 count,
AsyncProtocolRequest asyncRequest)
at
System.Net.Security._SslStream.ProcessRead(Byte[]
buffer, Int32 offset, Int32 count,
AsyncProtocolRequest asyncRequest)
at System.Net.TlsStream.Read(Byte[]
buffer, Int32 offset, Int32 size) at
System.Net.PooledStream.Read(Byte[]
buffer, Int32 offset, Int32 size) at
System.Net.Connection.SyncRead(HttpWebRequest
request, Boolean userRetrievedStream,
Boolean probeRead)
Exception Message: An existing
connection was forcibly closed by the
remote host
Stack Trace: at
System.Net.Sockets.NetworkStream.Read(Byte[]
buffer, Int32 offset, Int32 size)
I know this is old but for someone finding this : I had the same Exception . I figured out the error by defining a trace in 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.
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;

Resources