Basic post to test web service - asp.net

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

Related

Send Email using SMTP in web api vs asmx service

I am trying to send notification email in ASP.NET Web API. Following is the code
[HttpPost]
[Route("api/UpdateUser")]
public Foo UpdateUser(Foo vm)
{
/* some data base operations here....
......
......
*/
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("<SMTP Server>", 587);
mail.From = new MailAddress("test#test.com");
mail.To.Add("toemail#test.com");
mail.Subject = "You are subject";
mail.IsBodyHtml = true;
mail.Body = "Hello My Dear User";
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Foo newVM = new Foo();
}
But it throws following error:
System.Net.Mail.SmtpException: Failure sending mail.
---> System.Net.WebException: Unable to connect to the remote server
---> System.Net.Sockets.SocketException: A connection attempt failed because the connected
party did not properly respond after a period of time, or established connection failed
because connected host has failed to respond <server IP>:587
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace
--- at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message)
Now, i created an entirely new asp.net web project and placed same code in an asmx service (SOAP), and call it using soap client tools, it works just fine..
i deployed both in two separate IIS applications on same (test environment)server, only difference is web.api is a part of a ASP.NET MVC Application where as asmx service part of asp.net web application.
Result:
asmx service works but WEB API errors out with above error message.
Question is why ? what am i missing ?
I searched around and found following configuration could help
<system.net>
<defaultProxy>
<proxy usesystemdefault="False"/>
</defaultProxy>
:( but unfortunately in my case it didn't help...
Any one faced such issue ?
try this
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress("yourmail");
mailMessage.To.Add("akash073#waltonbd.com");
mailMessage.CC.Add("akash073#gmail.com");
mailMessage.Subject = "Test";
mailMessage.Body = "Test";
var smtp = new SmtpClient();
smtp.Host = "your host";
smtp.Port = 25;//your port
smtp.Credentials = new System.Net.NetworkCredential("userName", "password");
smtp.Send(mailMessage);

webService request failed with HTTP status 404

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.

WebRequest handshake fails due to unexpected packet format

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.

.NET MVC 4 Membership.CreateUser() Security Exception Forms Authentication

I am getting the following error at this line of code...
MembershipUser newuser = Membership.CreateUser(usersvm.username, usersvm.password,
usersvm.email, null, null, true, null, out createStatus);
The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
[SecurityException: The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique. Inaccessible logs: Security.]
I also have this in the web.config file
<system.web>
<trust level="Full"/>
Here is some stack trace
MySql.Web.Security.MySQLMembershipProvider.WriteToEventLog(Exception e, String action) +380
System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +207
System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, MembershipCreateStatus& status) +26
I needed to add this writeExceptionsToEventLog = "false" in web.config like this
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider"/>
<add autogenerateschema="true" writeExceptionsToEventLog="false" ....

Web services return xml error

All of the sudden all of the calls to my web services get this error:
2010-11-04 17:42:16,321 [9] ERROR ABCKiosk - System.InvalidOperationException: Response is not well-formed XML. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.MoveToContent()
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)
--- End of inner exception stack trace ---
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ABCKiosk.WebServices.Services.ActivityLog(String kioskID, String KTID, String activityType, Int32 errorCodeFromIncentOne, String msgFromIncentOne, DateTime kioskTime) in D:\SMS SHANE\KIOSK\ABCNC_Kiosk\Implementation\Source Code\ABCKioskClient\ABCKiosk\Web References\WebServices\Reference.cs:line 121
at ABCKiosk.FrmMain.FrmMain_KeyUp(Object sender, KeyEventArgs e) in D:\SMS SHANE\KIOSK\ABCNC_Kiosk\Implementation\Source Code\ABCKioskClient\ABCKiosk\FrmMain.cs:line 110
Before every were fine :( anyone know where is the problem and how to solve this?
Many thanks!
UPDATE - PROVIDE MORE INFORMATION
Here is one of my web methods:
[WebMethod(EnableSession = true)]
public CommonResult ActivityLog(string kioskID, string KTID,
string activityType, int errorCodeFromIncentOne, string msgFromIncentOne, DateTime kioskTime)
{
XMLParser parser = new XMLParser(Server.MapPath(Constant.XML_CONFIGURATION_FILE_PATH));
CommonResult result = new CommonResult();
try
{
AccountDAO accountDAO = new AccountDAO();
ActivityLogDAO activityLogDAO = new ActivityLogDAO();
KioskDAO kioskDAO = new KioskDAO();
// check if this kiosk is existed
if (!kioskDAO.IsKioskIDExisted(kioskID))
{
result.ErrorCode = Constant.ERROR_CODE_KIOSKID_NOT_EXISTED;
result.Message = "abc";
return result;
}
// check if this KTID is existed
if (!accountDAO.IsKTIDExisted(KTID))
{
result.ErrorCode = Constant.ERROR_CODE_KTID;
result.Message = "abc";
return result;
}
// check if this customer already logged for today
if (activityLogDAO.IsLoggedForToday(KTID, DateTime.Now))
{
result.ErrorCode = Constant.ERROR_CODE_LOG_LIMIT;
result.Message = "abc";
return result;
}
// begin log this activity to database
activityLogDAO.ActivityLog(KTID, kioskID, kioskTime);
// return success
result.ErrorCode = Constant.ERROR_CODE_SUCCESS;
result.Message = "abc";
return result;
}
catch (Exception e)
{
result.ErrorCode = Constant.ERROR_CODE_SYSTEM_ERROR;
result.Message = "abc";
return result;
}
}
UPDATE
I tried running the webmethod locally, inspected the return page and saw this in the page source:
<b> Description: </b>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.
<br><br>
<b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/ActivityLog'.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
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.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/ActivityLog'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405913
System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212
System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193
System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</pre></code>
I found out the bug myself, all because of a single line Response.Write() in the Session_Start() that mess up everything :(

Resources