none
Get JSON content from REST API using c# (have working javascript example) RRS feed

  • Question

  • Hello Everybody,

    For the last few hours I've been trying to receive a simple JSON object from a rest https api that requires username and password.

    The company provided a working example in Javasccript how to get the info. I don't know javascript, only c#, but I can't seem to make it work. Probably because I'm not familiar with wen http requests etc.

    This is the working JS code:

    function signin(){
                username = $('#inputUsername').val();
                pass = $('#inputPassword').val();
                if(pass.length > 0 && username.length > 0){
                    //Build post request
                    $.post( source+"/login", {username: username, password:pass}, function( data, textStatus, jqxhr ) {
                        $("header div h4#header_username").html(username);
                        token = data.auth;
                        $('#main-content').show()
                        $('#form-signin').hide()
                        populateVehicles();
                    });
                }
            }

    Could anyone help me convert it to c#? I've been trying to use HttpClient or HttpRequest and each time I receive a 401 Unauthorized Error or Bad Request Error.

    Thanks in advance.

    Found the solution. Sending the credentials worked only like this. Hope it helps.

                    var data = new NameValueCollection();
                    data["username"] = "USERNAME";
                    data["password"] = "PASSWORD";
    
                    var response = wb.UploadValues("URL", "POST", data);


    • Edited by Moshe Ligal Wednesday, July 25, 2018 2:45 PM SOLVED
    Tuesday, July 24, 2018 8:32 PM

All replies

  • What have you so far? You need (I guess) basic web credentials, something like

    using (WebClient client = new WebClient())
    {
        client.Credentials = new NetworkCredential("username", "password");
        //..
    }

    Wednesday, July 25, 2018 9:14 AM
  • https://msdn.microsoft.com/en-us/library/jj819168.aspx

    It's  Post request logic that you'll need. 

    I suggest that you post to the forum to find out what else you need to do to make contact with the API Restful Web service successfully.

    The 401 error means that the Restful services cannot authenticate the credentials that the client program is presenting.

    https://forums.asp.net/28.aspx/1?WCF+ASMX+and+other+Web+Services

    Wednesday, July 25, 2018 10:06 AM