I'm trying to log in to the website via C#
string url = "https://drs.zalohovysystem.sk/"
string param = "username=myusername&password=mypass";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = param.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
using (Stream stream = request.GetRequestStream())
{
byte[] paramAsBytes = Encoding.Default.GetBytes(param);
stream.Write(paramAsBytes, 0, paramAsBytes.Count());
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) //here i get error 405
{
foreach (var cookie in response.Cookies)
{
var properties = cookie.GetType()
.GetProperties()
.Select(p => new
{
Name = p.Name,
Value = p.GetValue(cookie)
});
foreach (var property in properties)
{
Console.WriteLine("{0}: {1}", property.Name, property.Value);
}
}
}
I get this:
Exception thrown: 'System.Net.WebException' in System.dll An unhandled exception of type 'System.Net.WebException' occurred in System.dll The remote server returned an error: (405) Method Not Allowed.
CodePudding user response:
The error message is telling the POST
method is not allowed on the endpoint. In such cases, the most common problems are:
- You may be using a wrong endpoint (which is the case here).
- You may be using the wrong HTTP method.
How to figure out the problem
- Open a browser like Chrome or Edge and browse to the login page
- Press F12 to open developer tools
- Select network tab, and make sure it's capturing the traffic (the record button should be red)
- enter credentials and press login button.
- See the request details, including request headers and payload tabs.
How to send the request and get response
You should send a:
POST
request tohttps://drs-function-prod.azurewebsites.net/api/v1/Auth/Login
endpoint- Set the
Content-Type: application/json
- Send a payload like
{"login":"[email protected]","password":"xyz"}
Then you will receive the following response:
For example:
static HttpClient client = new HttpClient();
private async void button1_Click(object sender, EventArgs e)
{
var jsonStr = JsonConvert.SerializeObject(new { login="[email protected]", password ="xyz" });
var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
var response = await client.PostAsync(
"https://drs-function-prod.azurewebsites.net/api/v1/Auth/Login", content);
MessageBox.Show($"Status: {response.StatusCode}\n"
$"{await response.Content.ReadAsStringAsync()}");
}
CodePudding user response:
Make sure Client Secret Key is correct, also try to set:
request.Accept= "/"; request.UserAgent = "MyApp";