I have problem with sending a big file via webService (System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse).
Everything works fine when the file is smaller then 20 MB, if it's bigger i get a response with 404 code.
Exception Information
Exception Type: System.Net.WebException
Status: ProtocolError
Response: System.Net.HttpWebResponse
Message: The request failed with HTTP status 404: Not Found.
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object[] ReadResponse(System.Web.Services.Protocols.SoapClientMessage, System.Net.WebResponse, System.IO.Stream, Boolean)
HelpLink: NULL
Source: System.Web.Services
StackTrace Information
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ie.osds.DocumentsTransferBLL.FSDMZRepositoryService.FileStreamingWebService.UploadScanning(DateTime DateCreated, String Title, String FileName, String ReferenceNumber, String Author, String DocumentType, XmlNode IndexData, Byte[] Content, Nullable`1 IsCompressed, Nullable`1 Version, DateTime DateReceived, String CreatedBy, String OrigDocumentGUID)
at ie.osds.DocumentsTransferBLL.Actions.ActionsHelper.UploadDocumentToDMZFileStreaming(FileStreamingWebService fsDMZWebService, SPQDocument spqDocument, String documentReferenceNumber, String documentAuthor, String documentType, Byte[] documentContent, String version, DateTime dateReceived)
at ie.osds.DocumentsTransferBLL.Actions.DocumentsUploadAction.Upload()*
Sounds like your file upload is timing out:
You can trap this error in your global.asax to see if this is the case:
Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As System.EventArgs)
Dim context As HttpContext = HttpContext.Current.ApplicationInstance.Context
If Not IsNothing(context) Then
If Not context.Response.StatusCode = HttpStatusCode.OK Then
'Detect file upload exceeded max length:
If context.Response.StatusCode = 404 And
context.Response.SubStatusCode = 13 Then
'clear the previous error page content:
context.Response.Clear()
'redirect to custom error page:
context.Server.Transfer("~/error.aspx?code=404.13", False)
End If
End If
End If
End Sub
You can also increase the request length in your web.config like so:
<system.web>
<httpRuntime maxRequestLength="29296" />
</system.web>
Note: Value is in Kbytes
If there is a webservice reference in web application just delete that then Rebuild,run the webservice and then again add that webservice reference to the web application.
Related
When I run the following line of code locally it runs succesfully. When I upload the code to the Arvixe web server I get the exception. I can read and write the temp folder as found by Path.GetTempPath()
I understand that XMLSerializer needs a temp path to create .DLLs. Does ASP.NET use a different temp path that it does not have permissions? I have compiled as Generate Serialization Assemblies Auto, Off and On to no avail. It must be a server setting as it runs on another Arvixe server but I dont know what to ask the server admins to do.
'This is the code line that causes the exception:
Sub Test
Dim formatter = New XmlSerializer(GetType(TestSMTPClass))
End Sub`
'This is a simple class we are trying to serialize
Public Class TestSMTPClass
Property ServerIP As String
Property Port As String
End Class
Throws this exception
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
ex.ToString
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at Microsoft.Win32.Fusion.ReadCache(ArrayList alAssems, String name, UInt32 nFlag)
at System.Reflection.RuntimeAssembly.EnumerateCache(AssemblyName partialName)
at System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadWithPartialName(String partialName, Evidence securityEvidence)
at System.Xml.Serialization.TempAssembly.LoadGeneratedAssembly(Type type, String defaultNamespace, XmlSerializerImplementation& contract)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at OCC_Competition.TestSMTP.btnTestCode_Click(Object sender, EventArgs e)
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.
I have a problem with logging. I have a class I use to log events, in my ASP.net application, to a text file. The class seems to work fine. Complications arise, though, because we are using a load balancer. We run our app on two servers. If one server fails, the load balancer will switch the web application to the other server. I can also direct the browser to specify which server to view the application on.
The problem is that when I go to one server, the application can log just fine. But if i try to switch to the other server, I get this error:
Exception Details: System.UnauthorizedAccessException: Access to the path '\myServer-qa\plantshare\someFolder\myApp\Logs\2012_12_14.txt' is denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in Explorer,
choose "Properties" and select the Security tab. Click "Add" to add
the appropriate user or group. Highlight the ASP.NET account, and
check the boxes for the desired access.
If i delete the file, which ever server creates it first will be fine but the other will fail. If i check the files permissions only the server that created it will have permission. Is this an issue with my code or IIS? Also, We use windows authentication. Here is the class I use to write:
Imports System.Net
Imports System.IO
Public Class logger
Private Shared _thisInstance As logger
Private Shared InstanceLock As New Object
Private Shared FileLock As New Object
Private _path As String
Public Property path() As String
Get
Return _path
End Get
Set(ByVal value As String)
_path = value
End Set
End Property
Protected Sub New(ByVal path As String)
Me.path = path
End Sub
Public Shared Function GetSingleton(ByVal path As String) As logger
SyncLock InstanceLock
If _thisInstance Is Nothing Then
_thisInstance = New logger(path)
End If
End SyncLock
Return _thisInstance
End Function
Private Function checkDir(ByVal path As String) As Boolean
Dim dir As New DirectoryInfo(path)
Dim exist As Boolean = True
If Not dir.Exists Then
Try
dir.Create()
Catch ex As Exception
exist = False
End Try
End If
Return exist
End Function
Private Function checkFile(ByVal path As String) As Boolean
Dim myFile As New FileInfo(path)
Dim exist As Boolean = True
Dim objWriter As IO.StreamWriter
Dim fs As FileStream
If Not myFile.Exists Then
Try
fs = New FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite)
objWriter = New System.IO.StreamWriter(fs)
objWriter.Close()
objWriter.Dispose()
fs.Close()
fs.Dispose()
Catch ex As Exception
exist = False
Finally
End Try
End If
Return exist
End Function
'updates file
Public Sub Logger(ByVal filePath As String, ByVal Message As String, ByVal title As String, Optional ByVal stkTrace As String = "")
Dim sw As StreamWriter
Dim fs As FileStream
Dim path As String
Dim now As DateTime = DateTime.Now
Dim today As String
today = Date.Now.ToString("yyy/MM/dd")
path = Me.path & today.Replace("/", "_") & ".txt"
If checkFile(path) Then
SyncLock FileLock
fs = New FileStream(path, FileMode.Append)
sw = New StreamWriter(fs)
Try
sw.WriteLine("Title: " & title)
sw.WriteLine("Message: " & Message)
sw.WriteLine("StackTrace: " & stkTrace)
sw.WriteLine("Date/Time: " & now.ToString("yyyy/MM/dd HH:mm:ss"))
sw.WriteLine("================================================")
sw.Flush()
Catch ex As Exception
Throw
Finally
sw.Close()
fs.Close()
sw.Dispose()
fs.Dispose()
End Try
End SyncLock
End If
End Sub
End Class
I have successfully returned data from a ASP.Net webservice in JSON format (using a service method that required no parameters) but have struggled with making a webservice call that requires a parameter.
Webservice:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function TestWebService(ByVal Description As String) As Stock
Dim res As New Stock(Guid.NewGuid, Description)
Return res
End Function
Object:
Public Class Stock
Public Sub New()
End Sub
Public Sub New(ByVal StockID As Guid, ByVal Description As String)
Me._StockID = StockID
Me._Description = Description
End Sub
Public Property StockID As Guid
Public Property Description As String
End Class
Javascript:
client = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
client.onreadystatechange = DataReturnedFromHttpRequest;
client.open("GET", "/MyWebService.asmx/TestWebService?" + JSON.stringify({"Description":["Test"]}), true);
client.setRequestHeader("Content-Type", "application/json");
client.send(null);
Response:
{
"Message": "Invalid web service call, missing value for parameter: \u0027Description\u0027.",
"StackTrace": " at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType": "System.InvalidOperationException"
}
I understand the error but cant seem to work out how to format my request correctly.
Finally got it... So for anyone curious the answer was trival.
The get request must be in the following format
/MyWebService.asmx/MyWebserviceMethod?Param1=%22ParamValue1%22&Param2=%22ParamValue2
Then it works like a charm.
I am working on form, which send input to webservice via post and display result. It must be simple, and it works fine on localhost. But when I try to use it agains live I have error 500.
Here is my code:
WebRequest request = WebRequest.Create("http://localhost:3192/WebServices/Export.asmx/" + uxAction.SelectedValue);
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(uxRequest.Text);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Flush();
requestStream.Close();
WebResponse response = request.GetResponse();
Stream newStream = response.GetResponseStream();
byte[] responseArray = new byte[response.ContentLength];
newStream.Read(responseArray, 0, (int)response.ContentLength);
newStream.Close();
uxResponse.Text = encoding.GetString(responseArray);
And here is information about error
Exception information:
Exception type: InvalidOperationException
Exception message: Request format is unrecognized for URL unexpectedly ending in '/GetProjectTypes'.
Request information:
Request URL: http://sitename.com/WebServices/Export.asmx/GetProjectTypes
Request path: /WebServices/Export.asmx/GetProjectTypes
User host address: 93.73.249.242
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 1
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath)
at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)
at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I also have http handler to access web services from javascript and this works fine:
<add verb="GET,HEAD,POST*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Here is my request data. Exception is same with or without it. Webservice do not have any parameters
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetProjectTypes xmlns="http://sitename.com/WebServices/Export.asmx" />
</soap:Body>
</soap:Envelope>
When we test webservice in browser, it adds methodname to url, but when we do post this is not needed.
I removed '/" + uxAction.SelectedValue' and everything is working fine now