使用c#使用凭据登录HttpRequest(获得有效的javascript代码)
在过去的5个小时里,我一直在尝试从一个需要使用.net C#登录的API获取JSON数据。 我尝试的每个组合都会导致“错误401-未经授权”。 我有一个Javascript的工作示例,也许这会有所帮助使用c#使用凭据登录HttpRequest(获得有效的javascript代码),javascript,c#,api,authentication,httprequest,Javascript,C#,Api,Authentication,Httprequest,在过去的5个小时里,我一直在尝试从一个需要使用.net C#登录的API获取JSON数据。 我尝试的每个组合都会导致“错误401-未经授权”。 我有一个Javascript的工作示例,也许这会有所帮助 function signin(){ username = $('#inputUsername').val(); pass = $('#inputPassword').val(); if(pass.length > 0 &
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();
});
}
}
在c#上,我尝试了许多代码组合,包括:
NetworkCredential netCredential = new NetworkCredential("USERNAME", "PASSWORD");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = netCredential;
request.Method = "POST";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("USERNAME" + ":" + "PASSWORD"));
//request.PreAuthenticate = false;
//request.Proxy.Credentials = CredentialCache.DefaultCredentials;
//request.UseDefaultCredentials = true;
//string base64Credentials = GetEncodedCredentials();
//request.Headers.Add("Authorization", "Basic " + base64Credentials);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
有些代码有“/”,因为我尝试过各种变体
我不懂
提前谢谢
function signin(){
var formData = new FormData();
formData.append('userame', document.getElementById('inputUsername').value);
formData.append('password', document.getElementById('inputPassword').value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.yoursite.com/login-url-here', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4){
var data = xhr.responseText;
if(data){
if(data == 'success'){
// yes your login page return success, do something below
document.getElementById('main-content').style.display = 'block';
document.getElementById('form-signin').style.display = 'none';
populateVehicles();
alert('login success')
} else {
alert('ops, failed to login, the page print this messages '+ data)
}
} else {
alert('ops your login page not print anything')
}
}
}
xhr.send(formData);
}
使用doetnet core 2.1,下面是一个基本示例。我检查了jquery文档,我认为您的js示例发送表单编码数据。您可以在浏览器的“开发人员工具”>“网络”选项卡中轻松检查这一点 表单编码 标题内容类型:application/x-www-form-urlencoded s、 a Json内容 “json”意味着它将生成一个请求,如下所示
{ "say": "Hi", "to": "Mom" }
标题内容类型为:application/json
请注意,HttpClient是线程安全的,如果您执行多个请求,则应首选单个实例
如果您使用的是dotnet core,以下文章将帮助您开始使用HttpClient:
请参阅@Archer提到的内容,以了解c#中不同http客户端库的概况。Javascript版本只是将用户名和密码作为post数据传递。我不确定NetworkCredential类的用途,但我猜您只是想将数据发布到/login,而不尝试使用它。只需将其作为普通对象传递(
JsonConvert.SerializeObject()
),就像在JavaSacriptor中一样谢谢。您能添加一个示例代码吗?我试过了,但我遇到了麻烦。不确定要保留哪些行和删除哪些行。谢谢。我得到的是“不允许使用方法”,而不是JSON文件。我做错了什么|“不允许使用方法”应该是服务器的答案。“method”是请求中的“POST/GET/”信息。所以这里的意思应该是:不允许您将POST消息发送到此路径。由于您的js示例使用post和works,我猜您使用了错误的url。我会仔细检查debugger.OP中的请求对象是否有一个工作的Javascript示例。他们想在C#中做同样的事情。
say=Hi&to=Mom
using (var client = new HttpClient())
{
var response = await client.PostAsync("https://myaddress.com/path", new StringContent(JsonConvert.SerializeObject(new
{
username = "user",
password = "password"
}), Encoding.UTF8, "application/json"));
if (response.StatusCode == HttpStatusCode.OK)
{
var responseString = await response.Content.ReadAsStringAsync();
// do something
}
}
{ "say": "Hi", "to": "Mom" }