Post file to ashx page on different server - asp.net

I have a asp.net web site where the user chooses some files with a fileUpload Control. Then the files need to be posted to another server
My domain is [http://www.mydomain.com]
The address where i have to upload the files is something like: [https://www.externaldomain.com/upload.ashx?asd2t423eqwdq]
I have tried the following:
Dim uploadedFiles As HttpFileCollection = Request.Files
Dim userPostedFile As HttpPostedFile = uploadedFiles(0)
Dim filePath As String
filePath = "https://www.externaldomain.com/upload.ashx?asd2t423eqwdq" & "/" & userPostedFile.FileName
userPostedFile.SaveAs(filePath)
But i get an error:
The SaveAs method is configured to require a rooted path, and the path 'https://www.externaldomain.com/upload.ashx?asd2t423eqwdq/Core CSS 3.pdf' is not rooted
I searched the internet, but all i could find were examples on how to upload to the page's server.
EDIT:
I used HttpWebRequest to access the link and it partialy worked. I also need to send 2 POST parameters, username and password.
This is how my code looks like now:
Dim link As String = "https://www.externaldomain.com/upload.ashx?e9879cc77c764220ae80"
Dim req As HttpWebRequest = WebRequest.Create(link)
Dim boundary As String = "-----"
req.ContentType = "multipart/form-data; boundary=" + boundary
req.Method = "POST"
Dim username As String = "test"
Dim userpass As String = "123456"
Dim credentials() As Byte = Encoding.UTF8.GetBytes("username=" & username & "&password=" & userpass & "--\r\n" & boundary & "--\r\n")
Dim separators() As Byte = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n")
Dim uploadedFiles As HttpFileCollection = Request.Files //this is where i take the file that the user wants to upload
Dim userPostedFile As HttpPostedFile = uploadedFiles(0)
//i convert the file to a byte array
Dim binaryReader As IO.BinaryReader
Dim fileBytes() As Byte
binaryReader = New BinaryReader(userPostedFile.InputStream)
fileBytes = binaryReader.ReadBytes(userPostedFile.ContentLength)
//'get the request length
req.ContentLength += credentials.Length
req.ContentLength += userPostedFile.ContentLength
req.ContentLength += separators.Length
req.ContentLength += 1
Dim dataStream As Stream
dataStream = req.GetRequestStream
dataStream.Write(credentials, 0, credentials.Length)
dataStream.Write(separators, 0, separators.Length)
dataStream.Write(fileBytes, 0, fileBytes.Length)
dataStream.Close()
Dim response As HttpWebResponse = req.GetResponse
The error i get is "forbidden". The username and password are 100% correct. I think the problem is that i do not create the request correctly. If i post only the credentials i get the error saying that i have no file...
Any ideas?

Eventually I used the code provided here http://aspnetupload.com/
I compiled it into a dll and added a reference to my solution.
It works :)

Related

Authenticating using OATH2 on Azure app registration works fine on IIS express, but fails in IIS

I have an application that I am trying to add a layer of SSO, authenticating against Azure AD app registration. The code works fine running in IIS Express, but fails with a 400 Bad Request whenever I attempt to run it from any IIS environment, including localhost.
I have a working function that requests an authorisation code, which works with no issues and the code is returned in the querystring. The issue happens in the next stage, where I use that code to retrieve the user's Sub ID from Microsoft. This is the code I have:
'Get the base azure values
Dim AzureClient As String = ClientInfo
Dim AzureSecret As String = AzureSecret
Dim AuthRedirectUri As String = "The address of the page"
Dim TenantID As String = AzureTenantID
Dim codeVerifier = Verifier string passed in earlier function
Dim httpWReq As HttpWebRequest = DirectCast(WebRequest.Create("https://login.microsoftonline.com/" & TenantID & "/oauth2/v2.0/token"), HttpWebRequest)
httpWReq.Method = "POST"
httpWReq.Host = "login.microsoftonline.com"
httpWReq.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = "client_id=" & AzureClient
postData += "&scope=openid&20email&20profile"
postData += "&code=" & Code
postData += "&redirect_uri=" & AuthRedirectUri
postData += "&grant_type=authorization_code"
postData += "&code_verifier=" & codeVerifier
postData += "&client_secret=" & AzureSecret
Dim encoding As New ASCIIEncoding()
Dim byteArray As Byte() = encoding.GetBytes(postData)
' Set the ContentLength property of the WebRequest.
httpWReq.ContentLength = byteArray.Length
Using streamWriter = New StreamWriter(httpWReq.GetRequestStream())
streamWriter.Write(postData)
End Using
' Get the response.
Dim response As WebResponse = httpWReq.GetResponse() <--- This is where the 400 Bad Request is thrown in IIS, but not IIS Express
Dim responseString As String = New StreamReader(response.GetResponseStream()).ReadToEnd()
Dim o As OAuth2AccessTokenReponse = DirectCast(JsonConvert.DeserializeObject(responseString, GetType(OAuth2AccessTokenReponse)), OAuth2AccessTokenReponse)
Dim IDToken As String = o.id_token
Dim stream = IDToken
Dim handler = New JwtSecurityTokenHandler()
Dim jsonToken = handler.ReadToken(stream)
Dim tokenS = TryCast(jsonToken, JwtSecurityToken)
Dim subID = tokenS.Claims.First(Function(claim) claim.Type = "sub").Value
Return subID
I've compared the calls coming from both environments and they are identical. I have both localhost addresses (localhost IIS address and IIS Express port) so the only differences are the port numbers used in the redirect URI field.
Does anyone have any idea what could be throwing this?
Problem sorted. After much, much digging about I found that IIS was still supporting TLS1.0 - removed that and everything works fine now.

How download more than one zip file using asp.net

I have five zip file in temp folder for download that file. My aim is download all file but now it download first file.
I try this code for download all file
Dim i As Integer
Dim TxtLocalSysName As String = Request.UserHostName
Dim readStream As FileStream
Dim writeStream As FileStream
Try
For i = 0 To lstdownload.Items.Count - 1
Dim filePath As String = Me.Label5.Text + "\" + lstdownload.Items(i).Text
Dim targetFile As System.IO.FileInfo = New System.IO.FileInfo(filePath)
readStream = New FileStream(filePath, FileMode.Open)
Dim length As Integer = Convert.ToInt32(readStream.Length)
'This is the buffer.
Dim byteFile() As Byte = New Byte(length) {}
readStream.Read(byteFile, 0, length)
readStream.Close()
Dim localPath As String = "\\" & TxtLocalSysName & "\c$\downloads"
If Not Directory.Exists(localPath) Then
Directory.CreateDirectory(localPath)
End If
writeStream = New FileStream(localPath & "\" & targetFile.Name, FileMode.Create)
writeStream.Write(byteFile, 0, length)
writeStream.Close()
Next i
Catch ex As Exception
Console.WriteLine("The process failed: {0}", ex.ToString())
Finally
readStream.Close()
readStream.Dispose()
writeStream.Close()
writeStream.Dispose()
End Try
I put the website in server side so all zip file download in server side temp folder. I need all zip file in client side temp folder

Capture response stream and output to file

We are using an online pdf encoding service where we send them the raw html and they return the pdf document. We want to take the WebResponse and immediately download it as a file to their desktop. This seems so straightforward and yet I can't seem to capture the stream correctly for download. I've tried many different approaches but I always end up with a 0 byte file for download. This is my latest incarnation which has gotten overly complicated but it still doesn't work.
Dim request = DirectCast(HttpWebRequest.Create(Url), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Using dataStream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
Try
Dim response As WebResponse = request.GetResponse
Dim bytes As Byte()
Using st As Stream = response.GetResponseStream
Dim ByteList As New ArrayList
Dim reader As New BinaryReader(st)
Dim length As Integer
While (InlineAssignHelper(bytes, reader.ReadBytes(1024))).Length > 0
ByteList.Add(bytes)
length += bytes.Length
bytes = New Byte(length - 1) {}
Dim position As Integer = 0
For Each b As Byte() In ByteList
Array.Copy(b, 0, bytes, position, b.Length)
position += b.Length
Next
End While
End Using
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf")
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Report Detail.pdf; size={1}", "attachment", bytes.Length.ToString()))
HttpContext.Current.Response.BinaryWrite(bytes)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Close()
HttpContext.Current.Response.End()
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function

How to show a pdf file in a web page present on secured web hosting

I am trying to show a pdf file in aspx page using FTP but always error 'File Not Found'
Here is my code..
Dim localFile As String = Server.MapPath("~/Test.pdf")
Dim URI As String = "ftp://mysitename/%2f/httpdocs/Folder1/Folder2/Folder3/image123.pdf"
Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
ftp.Credentials = New NetworkCredential("username", "password")
ftp.KeepAlive = False
ftp.UseBinary = True
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = CType(ftp.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
Response.Redirect("~/Test.pdf")
This code runs perfectly from VS2012 because the Test.pdf file is created where the .sln file resides. But when uploaded in web hosting it shows the error that :
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
I also tried..
Dim localFile As String = HttpContext.Current.Server.MapPath("~/Test.pdf")
Dim localfile As String = HostingEnvironment.MapPath("~/Test.pdf")
But all in vein..
Please help. Thanks..

What are valid values for the MediaType Property on a HttpWebRequest

What are valid values for the MediaType Property on a HttpWebRequest?
I want to do something like this:
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim req As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(New Uri(url)), System.Net.HttpWebRequest)
' Add the current authentication cookie to the request
Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)
Dim authenticationCookie As New System.Net.Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority)
req.CookieContainer = New System.Net.CookieContainer()
req.CookieContainer.Add(authenticationCookie)
req.MediaType = "PRINT"
Dim res As System.Net.WebResponse = req.GetResponse()
'Read data
Dim ResponseStream As Stream = res.GetResponseStream()
'Write content into the MemoryStream
Dim resReader As New BinaryReader(ResponseStream)
Dim docStream As New MemoryStream(resReader.ReadBytes(CInt(res.ContentLength)))
Thanks.
I think this wikipedia page should give you a fairly comprehensive list of media types:
Media Types

Resources