我正在尝试将值发布到服务器身份验证方法http:// * / Token。从我的C#客户端我得到400错误请求错误。虽然它在jquery中运行良好。
jQuery代码:
$( "#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#代码
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) {
}
我也尝试过创建本地json
var x = new
{
grant_type = "password",
username = "****@gmail.com",
password = "***"
};
但仍然是同样的错误。
从C#客户端调用服务器有什么我应该做的额外工作吗?
请帮忙, 感谢
答案 0 :(得分:0)
jQuery的ajax()
的{{1}}参数不包含json对象,而是一个后来被转换为post参数的对象(例如data
)。
所以试试:
?var1=foo&var2=bar
答案 1 :(得分:0)
解决:
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;
}
}