The remote server returned an error: (405) Method

2019-08-15 17:41发布

I want to use HttpWebRequest to post a file to the server:

private void testUpload()
{
    FileStream source = File.Open(@"C:\test.txt", FileMode.Open);

    var request = 
    (HttpWebRequest)WebRequest.Create(new Uri("http://example.com/Project/"));
    request.Method = "POST";

   request.BeginGetResponse(DataUploadCompleted, request);
}

private void DataUploadCompleted(IAsyncResult ar)
{
    var request = (HttpWebRequest)ar.AsyncState;
    var response = request.EndGetResponse(ar);
}

I got this exception:

The remote server returned an error: (405) Method Not Allowed.

When I access: "http://example.com/Project/", the page shows:

Directory Listing Denied

This Virtual Directory does not allow contents to be listed.

However, I already chmod 777 for the folder: project and allow IIS user to upload files on it (full permission).

Why I got that exception?

I searched for a solution. Some people advices to use:

NetworkCredential myCred = new NetworkCredential("myusername", "mypassword");
request.Credentials = myCred;

Is myusername and mypassword the account of the FTP?

If I have to use FTP account, then I don't like that. Can I use some other credentials rather then FTP account? Because I don't want to give the ftp account and people will access on my server.

3条回答
唯我独甜
2楼-- · 2019-08-15 18:00

go to IIS and then open directory browsing and enable it, this should work

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-15 18:00

I need to add a webpage on the server to handle the uploading.

查看更多
Lonely孤独者°
4楼-- · 2019-08-15 18:05

Sometimes this error for IIS config in the server you want "GetResponse();".

For preventing attack the server by lots of request to Web Api , IIS check user-agent and when there is not user-agent Server return 405 error.

You must set user-agent for example browser user-agent for passing this error.

see this code and use it in your code :

var request = (HttpWebRequest) WebRequest.Create(item.Url);

                request.Method = WebRequestMethods.Http.Get;
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; ; rv:1.8.0.7) Gecko/20060917 Firefox/1.9.0.1";
                request.AllowAutoRedirect = true;
                request.Timeout = 1000 * 300;
                request.KeepAlive = false;
                request.ReadWriteTimeout = 1000 * 300;
                request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
查看更多
登录 后发表回答