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

I used the following code to call a web service written in C# and hosted in IIS, but it returns an error

Remote server returned an error: (405) Method not enabled

But when I use Postman with the same input info, it works fine.

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url_to_post);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.KeepAlive = true;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    streamWriter.Write(json_object);
    streamWriter.Flush();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
    // return result;
}

Upvotes: 0

Views: 2482

Answers (1)

Jokies Ding
Jokies Ding

Reputation: 3494

First of all, please capture the request fiddler and check its response server.

We need to figure out where the 405 come from. If the response server is HTTP API/2.0 then it must come from http.sys. You may need to check your request URL.

However, if the response server is IIS. Then please enable failed request tracing. Most of time, IIS will return 405 error because either IIS use the wrong handler or your correct handler didn't allow POST method.

So please enable failed request tracing and check what module/handler is returning 405 error.

https://learn.microsoft.com/en-us/iis/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis

Please ensure WebDAV handler is not handling the request. And Static content feature has been installed. You need to ensure correct handler is handling the request and the handler also allow the POST method.

enter image description here

Upvotes: 1

Related Questions