问题描述:

I am trying to post values to server authenticate method http://*/Token . From my C# client i get 400 Bad request error. While it works fine in jquery.

jQuery Code:

$( "#post2").click(function() {

var Email=$('#Email').val();

var Password=$('#Password').val();

$.ajax({

type:"Post",

url: "http://***/Token",

data:{

"grant_type": "password",

"username": Email,

"password": Password

},

success: function(msg)

{

user=msg["access_token"];

console.log(JSON.stringify(msg));

}

});

});

C# code

string email = "***@gmail.com";

string password = "***";

var tok = new TokenModel{grant_type = "password", username = email, password = password};

var s = JsonConvert.SerializeObject (tok);

var request = HttpWebRequest.Create (string.Format (@"http://***/Token", ""));

request.ContentType = "application/json";

request.Method = "POST";

using (var writer = new StreamWriter (request.GetRequestStream ())) {

writer.Write (s);

}

using (HttpWebResponse responses = request.GetResponse () as HttpWebResponse) {

}

I also tried by creating local json

var x = new

{

grant_type = "password",

username = "****@gmail.com",

password = "***"

};

But still the same error.

Is there anything i should do extra for making this call to server from C# client?

Please help,

Thanks

网友答案:

jQuery's ajax()'s data parameter doesn't contain a json object, but an object which later gets transformed into the post arguments (such as ?var1=foo&var2=bar).

So try:

using (WebClient client = new WebClient())
{
    byte[] response = client.UploadValues("http://***/Token", new NameValueCollection()
    {
        { "grant_type", "password" },
        { "username", "****@gmail.com" },
        { "password", "*****" }
    });
}
网友答案:

Solved:

    public async Task<string> Login(string username, string password)
    {

        HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", "http://***.net/")));
        request.Method = "POST";

        string postString = String.Format("username={0}&password={1}&grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
        byte[] bytes = Encoding.UTF8.GetBytes(postString);
        using (Stream requestStream = await request.GetRequestStreamAsync())
        {
            requestStream.Write(bytes, 0, bytes.Length);
        }

        try
        {
            HttpWebResponse httpResponse =  (HttpWebResponse)(await request.GetResponseAsync());
            string json;
            using (Stream responseStream = httpResponse.GetResponseStream())
            {
                json = new StreamReader(responseStream).ReadToEnd();
                Console.WriteLine(json);
            }
            TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
            return tokenResponse.AccessToken;
        }
        catch (Exception ex)
        {
            Console.WriteLine ("h..........." + ex);
            //throw new SecurityException("Bad ls", ex);
            return null;
        }
    }
相关阅读:
Top