error: (405) Method Not Allowed when uploading file to https - c#

Wrote a code to upload file to a https folder as below
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = #"https://www.example.net/mydocs";
webClient.UseDefaultCredentials = true;
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(webAddress , "PUT", #"C:\d\1.xml");
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
the line webClient.UploadFile(webAddress , "PUT", #"C:\d\1.xml");
returning an error
The remote server returned an error: (405) Method Not Allowed.

Looks like the method PUT is not supported on the server. Make sure it's the correct method supported. You can try with POST
webClient.UploadFile(webAddress , "POST", #"C:\d\1.xml");

Related

The request was aborted: Could not create SSL/TLS secure channel. when calling PostAsJsonAsync

I am sending a request to third party website by PostAsJsonAsync as below:
var nbParamsJson = Newtonsoft.Json.JsonConvert.SerializeObject(nbParams);
var httpContent = new StringContent(nbParamsJson);
try
{
var response = await client.PostAsJsonAsync(siteUrl, httpContent);
}
catch (Exception exp)
{
}
which throws an exception: [The request was aborted: Could not create SSL/TLS secure channel.]
I know my website in test environment does not have a SSL certificate and probably is happening because the third-party website has SSL certificate.
I want to know is there any way to create SSL channel without moving to SSL.
I just added
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
before PostAsJsonAsync and it solved my issue.
I'm not sure of your async, but here is an adaptation from working code to send JSON data to an SSL website that you should be able to adapt to your specific case:
var baseurl = "https://example.com/api/upload/123";
var rqst = (HttpWebRequest)WebRequest.Create(baseurl);
rqst.Method = "PUT";
rqst.Accept = "application/json";
var authInfo = "authtoken";
rqst.Headers["Authorization"] = "Token " + authInfo;
rqst.UserAgent = "curl/7.37.0";
rqst.ContentType = "application/json; charset=utf-8";
using (var streamWriter = new StreamWriter(rqst.GetRequestStream()))
{
streamWriter.Write(GetJsonData());
}
try
{
var resp = rqst.GetResponse();
using (var sr = new StreamReader(resp.GetResponseStream() ?? throw new InvalidOperationException()))
{
var txt = sr.ReadToEnd();
textBox1.Text = txt;
}
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}

C# The remote server returned an error (401) unauthorized

I am trying to download a xml file from an url but I get this error:
"The remote server returned an error (401) unauthorized". Also, this webpage needs some credentials.
I searched on different topics before coming to ask you, but I didn't find a solution to this...
Here are two versions of codes I tried but didn't work:
try
{
WebClient wClient = new WebClient();
wClient.Credentials = new NetworkCredential(nni, pwd);
var dlString = wClient.DownloadString(url);
//Stream data = wClient.OpenRead(url);
//var reader = new XmlTextReader(wClient.OpenRead(url));
//doc.LoadXml();
doc.Load(wClient.OpenRead(url));
Console.WriteLine(doc.InnerText);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(xmlUrl);
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(nni, pwd);
string htmlCode = client.DownloadString(xmlUrl);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Can you guys please help me on this?

Error 403: Forbidden when trying to make a POST API call

I have a Dot Net application, built with C# and MVC. I have to use a SOAPUI API, but I'm getting an error 403 when trying to perform this, even though I have access to a P12 certificate and its password. I've pasted the code below, having skipped any unimportant parts.
public string anotherPostDataAttempt()
{
try
{
X509Certificate2 cert = new X509Certificate2
(#"C:\Users\...\Visual Studio 2015\Projects\...\certificateFile.P12", "thisIsThePassword");
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(True);
string url = "https://...";
//HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string xmlString = "";
StreamReader f_read = new StreamReader(#"C:\Users\...\Desktop\testFile.xml");
xmlString = f_read.ReadToEnd();
f_read.Close();
string DataToPost = xmlString;
String result = "";
String strPost = "RequestXML=" + DataToPost;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
//objRequest.ContentType = "text/xml; charset=utf-8";
objRequest.ContentType = "application/x-www-form-urlencoded";
//objRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
objRequest.ClientCertificates.Add(cert);
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
//
}
finally
{
myWriter.Close();
}
//The program crashes on the line below
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
For the record, I've already consulted this blog post in the subject matter but I'm guessing I must be doing something wrong after all, or I wouldn't be getting this error.
Full error:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
InnerException: Null.
Message: The remote server returned an error: (403) Forbidden.

upload file to https webserver using c# client

I want to upload a file securely from client machine to a webserver using C# client. It will be helpful to get some sample application of this. Also I want to know how can I achieve this with ssl certificate.
Thanks,
Abdul
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = #"http://myCompany/ShareDoc/";
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(webAddress + logFileName, "PUT", logFileName);
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}

Uploading file using Httpwebrequest

I want to upload file to a server. I wrote this function to upload the file to localhost server (I am using wamp server):
private void button1_Click_1(object sender, EventArgs e)
{
FileStream fstream = new FileStream(#"C:\Users\Albert\Documents\10050409_3276.doc", FileMode.OpenOrCreate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/upload_file");
request.Method = "PUT";
request.ContentLength = fstream.Length;
request.AllowWriteStreamBuffering = true;
Stream request_stream = request.GetRequestStream();
byte[] indata = new byte[1024];
int bytes_read = fstream.Read(indata, 0, indata.Length);
while (bytes_read > 0)
{
request_stream.Write(indata, 0, indata.Length);
bytes_read = fstream.Read(indata, 0, indata.Length);
}
fstream.Close();
request_stream.Close();
request.GetResponse();
MessageBox.Show("ok");
}
So when i click on the button the exception apper said that:
Additional information: The remote server returned an error: (405) Method Not Allowed.
I tried to use "POST" instead of "PUT" so the program works and the message box appears to say 'ok', but when i open the localhost->upload_file(folder) Ididn't find any files.
I tested my program with wamp server => the problem occured.
I tested my program with real server and put in the network credentials and tried to upload to folder that has (777) permission => the problem occured.
So where is the problem exactly?
Thanks :)
try with webClient
WebClient client = new WebClient();
byte[] bret = client.UploadFile(path, "POST", FilePath);
//path==URL
//FilePath==Your uploading file path
or
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = #"http://localhost/upload_file/";
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
serverRequest.Credentials = CredentialCache.DefaultCredentials;
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(path, "POST", FilePath);
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
(code in or part i didn't tried )

Categories

Resources