0

I've written a python function to move a router's IO port via a HTTP post request with Basic Authentivation. This works fine. But now I'd like to implement the sam with C#.

Here is my python function:

def io_on(ip='192.168.2.1', username='adm', password='123456'):
if not isinstance(ip, str):
    print('not string')
try:
    payload ='_ajax=1&_web_cmd=%21%0Aio%20output%201%20on%0A'
    r = requests.post('http://{}/apply.cgi'.format(ip), auth=HTTPBasicAuth(username, password), data=payload, timeout=3)
    if r.status_code == 200:
        print('{} : IO ON'.format(ip))
    elif r.status_code == 401:
        print('{} : Auth error'.format(ip))
    else:
        print(r.status_code)

except Exception as e:
    print(e)

I've experimented with NetWorkCredentials with no success.

2 Answers 2

1

Something like this :

    try
    {
        string username = "adm", password = "123456";
        string payload = "http://192.168.2.1/apply.cgi/?_ajax=1&_web_cmd=%21%0Aio%20output%201%20on%0A";


        HttpClient client = new HttpClient();

        var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        HttpResponseMessage response = await client.GetAsync(payload);
        HttpContent content = response.Content;

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Success");
        }

        else if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            Console.WriteLine("Auth error");
        }
        else
        {
            Console.WriteLine(response.StatusCode);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
Sign up to request clarification or add additional context in comments.

7 Comments

This looks like a GET not a POST as per your paste
Could you please adjust it?
Just change this line request.Method = "POST"; to request.Method = "GET";
I did it, thanks. I still got an unauthorized packet. Here is how I do it now: pastebin.com/JFt6bjMY
You are still using POST
|
1

Here's my way to make POST with basic authentication.

var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{login}:{password}")));

using (var client = new HttpClient() { DefaultRequestHeaders = { Authorization = authValue } })
{
    HttpResponseMessage response = client.PostAsync("https://localhost:44396/Documentation/All?pageNumber=0&pageSize=10", httpContent).Result;
    if (response.IsSuccessStatusCode)
    {
        response = await response.Content.ReadAsStringAsync();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.