Large File Upload Using HttpHandler or HttpModule? - asp.net

I have a webform application. It required to be able to upload large file (100MB). I intended to use httpHandler and httpModule to split the file to chunk.
I also had a look at http://forums.asp.net/t/55127.aspx
But it is a very old post and I've seen some example on the internet using httpHandler.
e.g. http://silverlightfileupld.codeplex.com/
I'm not sure httpModule is still better then httpHandler.
Since httpModule apples to the request of the whole application, and I just want it apply to specify page.
Can anybody explain the shortcoming of httpHandler for large file upload clearly (if it has)?
If you know a good example without flash/silverlight , could you post the link here? thx
Edit: Would Like to see some Source Code example.

Why not try plupload which has lot of features with many fallbacks and here how it is done.
This is the http handler code:
Imports System
Imports System.IO
Imports System.Web
Public Class upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim chunk As Integer = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
Dim fileName As String = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
Dim fileUpload As HttpPostedFile = context.Request.Files(0)
Dim uploadPath = context.Server.MapPath("~/uploads")
Using fs = New FileStream(Path.Combine(uploadPath, fileName), If(chunk = 0, FileMode.Create, FileMode.Append))
Dim buffer = New Byte(fileUpload.InputStream.Length - 1) {}
fileUpload.InputStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, buffer.Length)
End Using
context.Response.ContentType = "text/plain"
context.Response.Write("Success")
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Related

Visual basic programmatically pass username and password to https url to make webbrowser display webpage and also download from webpage

With normal HTTP I can download upload and navigate to routers but I can't find any code to do any of that when the routers are on HTTPS.
To download I use this:
Try
My.Computer.Network.DownloadFile("http://" & "180.29.74.70" & "/cgi-bin/log.cgi", "C:\Users\ssb\Desktop\randomword.txt", "username", "password")
WebBrowser1.Refresh()
Catch ex As Exception
MessageBox.Show("Router not sufficient for operation Return for Inspection cannot download log file")
End Try
To upload a file I use this:
My.Computer.Network.UploadFile("C:\Users\ssb\Desktop\tomtn.txt", "http://" & "180.29.74.70" & "/cgi-bin/updateconfig.cgi", "username", "password")
To navigate to a web page on HTTP I use this:
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
But when I use HTTPS:
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
I get this security alert:
Then I click on yes and it goes to the page—but I need the code to bypass any security questions like these.
Even though they're loosely related, you've presented two separate questions here.
Why is the call failing when I use the WebBrowser control to load a page via HTTPS?
Why is the call failing when I use the DownloadFile() method to download a file via HTTPS?
First, you need to eliminate the possibility that your code is failing. Try both of the tasks above using public HTTPS URLs that are known to work correctly.
If you discover that the source of the problem is your private URL, you may want to consider whether you want to ignore SSL errors in your WebBrowser control.
You can do so using the (untested, translated to VB) code from this blog post:
Partial Public Class Form1
Inherits Form
Private WithEvents WebBrowser As New WebBrowser
Private Sub WebBrowser_DocumentCompleted(Sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
If e.Url.ToString() = "about:blank" Then
'create a certificate mismatch
WebBrowser.Navigate("https://74.125.225.229/")
End If
End Sub
End Class
<Guid("6D5140C1-7436-11CE-8034-00AA006009FA")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
<ComImport>
Public Interface UCOMIServiceProvider
<PreserveSig>
Function QueryService(<[In]> ByRef guidService As Guid, <[In]> ByRef riid As Guid, <Out> ByRef ppvObject As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface
<ComImport>
<ComVisible(True)>
<Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IWindowForBindingUI
<PreserveSig>
Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface
<ComImport>
<ComVisible(True)>
<Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IHttpSecurity
'derived from IWindowForBindingUI
<PreserveSig>
Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
<PreserveSig>
Function OnSecurityProblem(<[In], MarshalAs(UnmanagedType.U4)> dwProblem As UInteger) As Integer
End Interface
Public Class MyWebBrowser
Inherits WebBrowser
Public Shared IID_IHttpSecurity As New Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")
Public Shared IID_IWindowForBindingUI As New Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")
Public Const S_OK As Integer = 0
Public Const S_FALSE As Integer = 1
Public Const E_NOINTERFACE As Integer = &H80004002
Public Const RPC_E_RETRY As Integer = &H80010109
Protected Overrides Function CreateWebBrowserSiteBase() As WebBrowserSiteBase
Return New MyWebBrowserSite(Me)
End Function
Private Class MyWebBrowserSite
Inherits WebBrowserSite
Implements UCOMIServiceProvider
Implements IHttpSecurity
Implements IWindowForBindingUI
Private myWebBrowser As MyWebBrowser
Public Sub New(myWebBrowser As MyWebBrowser)
MyBase.New(myWebBrowser)
Me.myWebBrowser = myWebBrowser
End Sub
Public Function QueryService(ByRef guidService As Guid, ByRef riid As Guid, ByRef ppvObject As IntPtr) As Integer Implements UCOMIServiceProvider.QueryService
If riid = IID_IHttpSecurity Then
ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IHttpSecurity))
Return S_OK
End If
If riid = IID_IWindowForBindingUI Then
ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IWindowForBindingUI))
Return S_OK
End If
ppvObject = IntPtr.Zero
Return E_NOINTERFACE
End Function
Public Function GetWindow(ByRef rguidReason As Guid, ByRef phwnd As IntPtr) As Integer Implements IHttpSecurity.GetWindow, IWindowForBindingUI.GetWindow
If rguidReason = IID_IHttpSecurity OrElse rguidReason = IID_IWindowForBindingUI Then
phwnd = myWebBrowser.Handle
Return S_OK
Else
phwnd = IntPtr.Zero
Return S_FALSE
End If
End Function
Public Function OnSecurityProblem(dwProblem As UInteger) As Integer Implements IHttpSecurity.OnSecurityProblem
'ignore errors
'undocumented return code, does not work on IE6
Return S_OK
End Function
End Class
End Class
Regarding problem #2: It appears you may be confusing WebBrowser and DownloadFile(). As you've probably already discovered, the WebBrowser control doesn't download files. However, you can simulate the behavior using this technique:
Partial Public Class Form2
Inherits Form
Private Sub WebBrowser_Navigating(Sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser.Navigating
Dim sFilePath As String
Dim oClient As Net.WebClient
' This can be any conditional criteria you wish '
If (e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".pdf")) Then
SaveFileDialog.FileName = e.Url.Segments(e.Url.Segments.Length - 1)
e.Cancel = True
If SaveFileDialog.ShowDialog() = DialogResult.OK Then
sFilePath = SaveFileDialog.FileName
oClient = New Net.WebClient
AddHandler oClient.DownloadFileCompleted, New AsyncCompletedEventHandler(AddressOf DownloadFileCompleted)
oClient.DownloadFileAsync(e.Url, sFilePath)
End If
End If
End Sub
Private Sub DownloadFileCompleted(Sender As Object, e As AsyncCompletedEventArgs)
MessageBox.Show("File downloaded")
End Sub
Private WithEvents SaveFileDialog As New SaveFileDialog
Private WithEvents WebBrowser As New WebBrowser
End Class
In any event, the first step in solving this is to figure out whether it's your code or the private URL that's causing your issue.
The main thing needed here is to programatically download a file from a https url while using a username and password blocked by the security certificate issue
and the solution after searching for 2 weeks is
To Download a file you can disable the security cerificate request temporaraly with the following code then after the code ran it enables the security certicate again
First code you dont even need a browser it automatically saves the file to you desktop
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'check if a simular file doesnt exists so you can create a new file and deletes the file if it exists
If File.Exists("C:\pathtoyourfile\yourfilename.txt") Then
File.Delete("C:\pathtoyourfile\yourfilename.txt")
End If
'Type this before your download or hhtps request
'ByPass SSL Certificate Validation Checking
System.Net.ServicePointManager.ServerCertificateValidationCallback =
Function(se As Object,
cert As System.Security.Cryptography.X509Certificates.X509Certificate,
chain As System.Security.Cryptography.X509Certificates.X509Chain,
sslerror As System.Net.Security.SslPolicyErrors) True
'Call web application/web service with HTTPS URL here
'=========================================================================================
'ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
Try
My.Computer.Network.DownloadFile("https://176.53.78.22/filenameonserveryouwanttodownload", "C:\pathtoyourfile\yourfilename.txt", "Yourusername", "yourpassword")
WebBrowser1.Refresh()
Catch ex As Exception
MessageBox.Show("message saying something didnt work")
'exit sub if it worked
Exit Sub
End Try
MessageBox.Show(" message saying it worked")
'=========================================================================================
'Restore SSL Certificate Validation Checking
System.Net.ServicePointManager.ServerCertificateValidationCallback = Nothing
End Sub
then to browse to a webaddress the following code will popup and the security popup will popup but just select yes browsing on the webpage works normally
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
As you said:
[...] I need the code to bypass any security questions like these.
In other word, you need to "automatically accept self signed SSL certificate", so in my opinion it is a duplicate question with : VB .net Accept Self-Signed SSL certificate, which may fit your needs.
and most especially slaks answer:
In VB.Net, you need to write:
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications

Download PDF using Response on ASPX Page only working in Page_Load

I've seen several questions relating to downloading a PDF from a Web browser using Response, but none seem to fit the mysterious issue I'm having.
I am working on a project that requires the user to be able to click a button (btnPDF) to instantly download a PDF of a Telerik report with a specific "ID" string to the Downloads folder. This process was originally located in an ASPX Page on an IIS separate from where the button is located. When btnPDF was clicked, I used Response.Redirect to download the PDF through that page. The code to download the PDF looked like this:
Response.Clear()
Response.ContentType = result.MimeType 'this is always "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Expires = -1
Response.Buffer = True
Response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
Response.BinaryWrite(result.DocumentBytes)
Response.End()
Note that result.DocumentBytes is a byte array containing correct bytes for the PDF.
This code worked fine. Now, instead of having the process on a separate Page in a separate project, I need to merge the process onto the same page where btnPDFis located, so that when you click btnPDF, a subroutine is called that performs the same task. I thought this would be very easy, pretty much a copy and paste. With the same code added in a new subroutine, this is what my click event handler "ButtonPDF_Click" now looks like:
Protected Sub ButtonPDF_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPDF.Click
DownloadReportPDF(Me.RadGrid1.SelectedValue.ToString())
Dim strMessage As String = "alert('Printed PDF Sheet.');"
ScriptManager.RegisterStartupScript(Me, Me.GetType, "MyScript", strMessage, True)
End Sub
Protected Sub DownloadReportPDF(ByVal releaseMasterId As String)
'Service call to generate report source
Dim service As New TelerikReportLibrary.ReportServices.PPSReportService
Dim source As Telerik.Reporting.TypeReportSource = service.GetReportSource(releaseMasterId)
'Render PDF and download
Dim reportProcessor As New ReportProcessor()
Dim result As RenderingResult = reportProcessor.RenderReport("PDF", source, Nothing)
Dim fileName As String = result.DocumentName + "_" + releaseMasterId + "." + result.Extension
Response.Clear()
Response.ContentType = result.MimeType 'this is always "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Expires = -1
Response.Buffer = True
Response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
Response.BinaryWrite(result.DocumentBytes)
Response.End()
End Sub
But the PDF no longer downloads. An accurate byte array is still created, but the Response portion does not result in the PDF being downloaded from the browser. I've found that putting a call to DownloadReportPDF in the Page_Load handler on the same Page successfully generates and downloads a PDF as it did before.
I can't see any reason why this isn't working, but I'm new to ASP, and I'm not great in VB. I've tried using Response.OutputStream, Response.WriteFile, and making use of a MemoryStream, among several other things that I've lost track of. I'm hoping there's something simple, maybe some sort of property of the Page or btnPDF I could be missing. Here is the markup for btnPDF, just in case:
<asp:linkButton ID="btnPDF" CssClass="btn btn-default" runat="server" Width="115px">
<i class="fa fa-file-text" title="Edit"></i> PDF
</asp:linkButton>
What could be causing such a problem? Where should I look at this point?
Let me know if more information is needed.
Thanks,
Shane
EDIT:
I experimented with setting a session variable on btnPDF_Click, and handling the PDF download on postback. Again, a valid byte array was generated, but the HttpResponse did not cause the PDF to download from the browser.
EDIT:
Building on the last edit, this tells me that calling DownloadReportPDF from Page_Load works only when IsPostBack is false. I just tested this thought, and it holds true. In the above code, if I check IsPostBack at the moment I'm trying to download the PDF, it is true. Investigating further.
Alright, I finally found a solution I'm satisfied with (though I still don't understand why I can't download the PDF using Response while IsPostBack is true).
Inspired by this thread, I put the previously posted code in an HttpHandler called PDFDownloadHandler, then used Response.Redirect in the btnPDF_Click event handler to utilize PDFDownloadHandler. This article helped me a lot on that process, as it is something I have not done before.
In case anyone else runs into this problem, here is the new PDFDownloadHandler:
Imports Microsoft.VisualBasic
Imports System.Web
Imports Telerik.Reporting
Imports Telerik.Reporting.Processing
Public Class PDFDownloadHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As _
System.Web.HttpContext) Implements _
System.Web.IHttpHandler.ProcessRequest
Dim request As HttpRequest = context.Request
Dim response As HttpResponse = context.Response
Dim path As String = request.Path
If path.Contains("pps.pdfdownload") Then
Dim releaseMasterId As String = request.QueryString("ID")
If releaseMasterId IsNot Nothing Then
'Service call to generate report source
Dim service As New TelerikReportLibrary.ReportServices.PPSReportService
Dim source As Telerik.Reporting.TypeReportSource = service.GetReportSource(releaseMasterId)
'Render PDF and save
Dim reportProcessor As New ReportProcessor()
Dim result As RenderingResult = reportProcessor.RenderReport("PDF", source, Nothing)
Dim fileName As String = result.DocumentName + "_" + releaseMasterId + "." + result.Extension
response.Clear()
response.ContentType = result.MimeType
response.Cache.SetCacheability(HttpCacheability.Private)
response.Expires = -1
response.Buffer = True
response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
response.BinaryWrite(result.DocumentBytes)
End If
End If
response.End()
End Sub
Public ReadOnly Property IsReusable() As Boolean _
Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Any further insight on why the original technique did not work is greatly appreciated.

How to open varbinary word doc as HTML

I have a problem which I have not been able to find an answer to in months. I store word doc resumes as varbinary(max). I can retrieve the resumes based on a full-text search – no problem. But the resumes are retrieved as word documents in a .ashx file with the following code. I really need to implement hit highlighting on the site so that users can see if the returned resume is a good fit or not. I don’t think this can be done from an .ashx file, so I think I need to be able to open the resume as html in an aspx page and maybe use javascript to do the hit highlighting or perhaps return the text only content of the word document somehow and manipulate the text before display with html tags. I cant find anything anywhere which addresses the problem. I am really hoping that someone can point me in the right direction.
Thanks in advance for any advice.
Imports System.io
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
 
Public Class ReadResume : Implements IHttpHandler
Const conString As String = "Data Source=tcp:sql2k804.discountasp.net;Initial Catalog=SQL2008R2_284060_resumedata;User ID=SQL2008R2_284060_resumedata_user;Password=mypwd2314;"
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand("Select ResumeDoc, DocTypeExtension From ResumeTable WHERE CandidateId=#CandidateId", con)
Dim CId As String = System.Web.HttpContext.Current.Request.QueryString("Para")
cmd.Parameters.AddWithValue("#CandidateId", CId)
Using con
con.Open()
Dim myReader As SqlDataReader = cmd.ExecuteReader
If myReader.Read() Then
context.Response.Clear()
context.Response.ClearContent()
context.Response.ClearHeaders()
Dim file() As Byte = CType(myReader("ResumeDoc"), Byte())
Dim doc_type As String = CType(myReader("DocTypeExtension"), String)
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.ContentType = "Application/msword"
context.Response.AddHeader("content-disposition", "Candidate Resume")
context.Response.BinaryWrite(file)
End If
End Using
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
You can use Microsoft Office COM components to deal with Word documents. For example, that is the way to convert Word to HTML: http://rongchaua.net/blog/c-convert-word-to-html/
UPDATE:
There are other solutions.
If you have only .docx (not .doc) documents then you can use this simple code to extract plain text from docx documents: http://www.codeproject.com/KB/office/ExtractTextFromDOCXs.aspx This is the same code: http://conceptdev.blogspot.com/2007/03/open-docx-using-c-to-extract-text-for.html
There are some commercial libraries for reading/writing Word documents:
http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx
http://www.cellbi.com/Products.aspx

Upload files asynchronously with ASP.NET

I'm trying to make an asynchronous upload operation but I got this error message:
Error occurred, info=An exception
occurred during a WebClient request`.
Here's the upload function:
Private Sub UploadFile()
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
Dim client = New WebClient
AddHandler client.UploadFileCompleted, AddressOf UploadFile_OnCompleted
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim c As String = System.IO.Path.GetFileName(uploads(i).FileName)
Try
client.UploadFileAsync(uri, c)
Catch Exp As Exception
End Try
End If
Next i
End Sub
Public Sub UploadFile_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
Dim client As WebClient = CType(e.UserState, WebClient)
If (e.Cancelled) Then
labMessage.Text = "upload files was cancelled"
End If
If Not (e.Error Is Nothing) Then
labMessage.Text = "Error occured, info=" + e.Error.Message
Else
labMessage.Text = "File uploaded successfully"
End If
End Sub
Update 1:
Private Sub UploadFile()
Dim uploads As HttpFileCollection
Dim fileToUpload = "C:\Demo\dummy.doc"
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
Dim client = New WebClient
AddHandler client.UploadFileCompleted, AddressOf UploadFile_OnCompleted
client.UploadFileAsync(uri, fileToUpload)
End Sub
client.UploadFileAsync(uri, fileToUpload) is throwing this error message
Error occured, info=System.Net.WebException: The request was aborted: The request was canceled. at System.Net.FileWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
By calling GetFileName you're truncating whatever path information was there. You should provide UploadFileAsync with a full path name.
Also, replace e.Error.Message with just e.Error so you get the full error details including inner exceptions. This will provide more info and probably lead you to the answer.
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
The above statement is wrong, how come you have Uri as a file system path, it should be "http://" or "https://" , if you are trying to upload it to your local asp.net web site project then you must have a url something like http://localhost:PORT/UploadedUserFiles ... and you will know port number when you execute project.
Dim uri As Uri = New Uri("http://localhost:PORT/Upload.aspx")
Try this:
1) Create a new class MyWebClient.
Class MyWebClient
Inherits WebClient
Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
Dim req = MyBase.GetWebRequest(address)
Dim httpReq = TryCast(req, HttpWebRequest)
If httpReq IsNot Nothing Then
httpReq.KeepAlive = False
End If
Return req
End Function
End Class
2) Use this class instead of the default WebRequest.
Private Sub UploadFile()
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
Dim client = New MyWebClient
AddHandler ...
I hope this helps.
From the reference to HttpContext.Current.Request.Files I am assuming that your are running the code in a web project. You don't have to use WebClient to save the file to your disk. All you have to do is this:
Private Sub UploadFile()
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim path As String = "C:\UploadedUserFiles\"
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim p As String = System.IO.Path.Combine(path, System.IO.Path.GetFileName(uploads(i).FileName))
uploads(i).SaveAs(p)
End If
Next i
End Sub
I'm not that good with VB.. so there might be syntax problems :) bear with me..
You can't upload files from the ASP.NET web request asyncronously via this mechanism. The file is actually in the body of the http request so it is already on the server. Request.Files provides a stream to the files that are already on the server.
You could use something like Silverlight or Flash from the client side.
You might want to investigate the AJAX Control Toolkit and use the AsyncFileUpload control.
The control has a server side event when upload is complete. (UploadedComplete)
It also has a SaveAs(string filename) method for the uploaded file.
Simple Usage:
Markup
<asp:AsyncFileUpload ID="upload" runat="server" OnUploadedComplete="displayFile"/>
Code Behind
protected void displayFile(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
upload.SaveAs("C:\\text.txt");//server needs permission
}
Try to add Header information to the WebClient Object as below :
With webClient
.Headers.Add("Content-Type", Web.MimeMapping.GetMimeMapping("C:\filename.txt"))
.Headers.Add("Keep-Alive", "true")
.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
.Credentials = New Net.NetworkCredential("UserName", "password")
End With

Post XML to a web service

I have a web service, which accepts XML input. What I am trying to do is setup an aspx page which posts xml to the service. Here is my code so far, but I am getting an error 400 (bad request) when I try to submit...
Imports System.Net
Imports System.IO
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit.Click
Dim strDataToPost As String
Dim myWebRequest As WebRequest
Dim myRequestStream As Stream
Dim myStreamWriter As StreamWriter
Dim myWebResponse As WebResponse
Dim myResponseStream As Stream
Dim myStreamReader As StreamReader
' Create a new WebRequest which targets the web service method
myWebRequest = WebRequest.Create("http://foo/p09SoapHttpPort")
' Data to send
strDataToPost = DataToSend.Text & Server.UrlEncode(Now())
' Set the method and content type
With myWebRequest
.Method = "POST"
.ContentType = "text/xml"
.Timeout = -1
.ContentLength = strDataToPost.Length()
End With
' write our data to the Stream using the StreamWriter.
myRequestStream = myWebRequest.GetRequestStream()
myStreamWriter = New StreamWriter(myRequestStream)
myStreamWriter.Write(strDataToPost)
myStreamWriter.Flush()
myStreamWriter.Close()
myRequestStream.Close()
' Get the response from the remote server.
myWebResponse = myWebRequest.GetResponse()
' Get the server's response status
myResponseStream = myWebResponse.GetResponseStream()
myStreamReader = New StreamReader(myResponseStream)
ResponseLabel.Text = myStreamReader.ReadToEnd()
myStreamReader.Close()
myResponseStream.Close()
' Close the WebResponse
myWebResponse.Close()
End Sub
End Class
If anyone knows of any good web resources on how to upload .xml files to a web service method that would also be a great help and would answer this question as I can re-work it that way.
Thanks.
P.S in the last edit, I modified the code to have .contentlength (thanks for the assistance). Unfortunately after this I am still getting 'Bad Request'. If anyone can confirm / disconfirm my code should be working, I will start investigating the service itself.
The data you're trying to post might look a little funny if you're concatenating a time string to it:
strDataToPost = DataToSend.Text & Server.UrlEncode(Now())
If DataToSend is proper XML, then you're adding the Url Encoding of Now() which makes me think it will no longer be valid XML.
Check to make sure your StreamWriter is not inserting additional characters (CR, LF). If it does, then the length you're sending does not correspond to the actual data, but that probably wouldn't have caused a problem before you started sending the content length.
Is your web service configuration to accept XML directly? I'm wondering if you might have to encapsulate the XML in multipart/form-data in order for your web service to accept it.
I'm not a web service expert, but I compared your code to some working code I have, and the only relevant difference is that you are not setting the ContentLength of your request.
myWebRequest.ContentLength = strDataToPost.Length()

Resources