我有一个Asmx.Cs类,它从服务器调用Web API服务。当我从My Class调用API时,它返回" Authenticated Error" 但是,当我从Windows控制台应用程序(确切的代码,如我的asmx代码)调用它时,它运行正常!我知道这很奇怪,但确实发生了!
这是我在ASMX课程中的代码:
public class GetAccountNoByList : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetAccountNumberByList(string bsIdJsonList , int insuranceCompanyId = 0)
{
if (bsIdJsonList == "" || insuranceCompanyId == 0)
{
AccountNo Err = new AccountNo();
Err.ErrMsg = "Error";
return JsonConvert.SerializeObject(Err);
}
var accountNo = GettingAccountNo(bsIdJsonList, insuranceCompanyId);
return accountNo;
}
private string GettingAccountNo(string bsIdJsonList, int insuranceCompanyId)
{
string accountNo = "";
if (insuranceCompanyId == 5)
{
const string fullUrl = "MyApiURL";
const string userName = "xxxxx";
const string password = "yyyyy";
accountNo = GetDataFromWebAPI_AccountNO(bsIdJsonList, insuranceCompanyId, mainServerUrl, fullUrl, userName, password);
int xx = 0;
}
#endregion
return accountNo;
}
private string GetDataFromWebAPI_AccountNO(string bsIdJsonList, int InsuranceID, string MainServerUrl, string FullUrl, string UserName, string Password)
{
//List<AccountNo> accountNo = null;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
List<AccountNoToGet> accounts = new List<AccountNoToGet>();
accounts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AccountNoToGet>>(bsIdJsonList);
authenticationToken = "";
string txtServerUrlFinal = "";
if ((MainServerUrl.EndsWith("/") != true))
{
txtServerUrlFinal = "/";
}
// ''''''''''''''' Authenticate
HttpResponseMessage responseAuthenticate = null;
responseAuthenticate = SendRequest_authenticate( UserName, Password, HttpMethod.Post, (MainServerUrl
+ (txtServerUrlFinal + "api/Login")), null);
if (responseAuthenticate.IsSuccessStatusCode)
{
authenticationToken = responseAuthenticate.Headers.GetValues("authenticationToken").FirstOrDefault();
}
responseAuthenticate.Dispose();
// ''''''''''''''' GetData
foreach (var item in accounts)
{
string txtContentBody = ("{bsId: " + item.Bid.ToString() + "}");
HttpMethod method = HttpMethod.Post;
HttpResponseMessage responseGetData = null;
try
{
responseGetData = SendRequest_getDataAccountNumberList(UserName, Password, method, FullUrl, new StringContent(txtContentBody, Encoding.UTF8, "application/json"));
}
catch (Exception ex)
{
object x = 50;
}
if (responseGetData.IsSuccessStatusCode)
{
string ACCFinal = "";
JObject parsed = null;
parsed = JObject.Parse((responseGetData.Content.ReadAsStringAsync().Result));
AccountNoInformationReturn accountNoInformationReturn = new AccountNoInformationReturn();
accountNoInformationReturn.BsId = parsed.SelectToken("Data.BsId").ToString();
accountNoInformationReturn.CmnId = parsed.SelectToken("Data.CmnId").ToString();
accountNoInformationReturn.AccNo = parsed.SelectToken("Data.AccNo").ToString();
accountNoInformationReturn.CardNo = parsed.SelectToken("Data.CardNo").ToString();
accountNoInformationReturn.ShebaAcc = parsed.SelectToken("Data.ShebaAcc ").ToString();
accountNoInformationReturn.ErrMsg = parsed.SelectToken("Data.ErrMsg").ToString();
if (accountNoInformationReturn.ErrMsg != "")
{
ACCFinal = "-";
}
else if (accountNoInformationReturn.AccNo == "" & accountNoInformationReturn.CardNo == "" & accountNoInformationReturn.ShebaAcc == "")
{
ACCFinal = "-";
}
else
{
if (accountNoInformationReturn.CardNo.Length != 0) ACCFinal = accountNoInformationReturn.CardNo;
else if (accountNoInformationReturn.AccNo.Length != 0) ACCFinal = accountNoInformationReturn.AccNo;
else if (accountNoInformationReturn.ShebaAcc.Length != 0) ACCFinal = accountNoInformationReturn.ShebaAcc;
if (ACCFinal.Length == 0)
{
var ccc = 0;
}
var change = (from lst in accounts
where lst.Bid == item.Bid
select lst).FirstOrDefault();
if (change != null) change.ACC = ACCFinal;
}
}
else
{
return JsonConvert.SerializeObject(accounts);
}
}
return JsonConvert.SerializeObject(accounts);
}
private HttpResponseMessage SendRequest_authenticate(string userNameApi, string passwordApi, HttpMethod httpMethod, string strUri, HttpContent content = null)
{
System.Net.Http.HttpClient httpClient = new HttpClient();
// Warning!!! Optional parameters not supported
Uri uri;
uri = new Uri(strUri);
HttpRequestMessage request = new HttpRequestMessage(httpMethod, uri);
if (!string.IsNullOrEmpty(authenticationToken))
{
request.Headers.Add("authenticationtoken", authenticationToken);
}
// if(uriScheme == Uri.UriSchemeHttps)
// {
request.Headers.Add("username", userNameApi);
request.Headers.Add("password", passwordApi);
// }
request.Content = content;
HttpResponseMessage response = null;
try
{
response = httpClient.SendAsync(request).Result;
}
catch (Exception z)
{
object x = 20;
}
// txtLastRequestUrl.Text = uri.ToString();
if (!response.IsSuccessStatusCode)
{
// remark:response.ReasonPhrase is encoded at server for supporting persian
string reasonPhrase = System.Web.HttpUtility.UrlDecode(response.ReasonPhrase);
// txtLastResponseMessage = String.Format("{0}:{1} Details {2}", response.StatusCode, reasonPhrase, response.Content.ReadAsStringAsync.Result)
}
else
{
// txtLastResponseMessage = "Successful"
}
httpClient.Dispose();
return response;
}
string authenticationToken;
private HttpResponseMessage SendRequest_getDataAccountNumberList( string userNameApi, string passwordApi, HttpMethod httpMethod, string strUri, HttpContent content = null)
{
System.Net.Http.HttpClient httpClient = new HttpClient();
// Warning!!! Optional parameters not supported
Uri uri;
uri = new Uri(strUri);
HttpRequestMessage request = new HttpRequestMessage(httpMethod, uri);
if (!string.IsNullOrEmpty(authenticationToken))
{
request.Headers.Add("authenticationtoken", authenticationToken);
}
// if(uriScheme == Uri.UriSchemeHttps)
// {
request.Headers.Add("username", userNameApi);
request.Headers.Add("password", passwordApi);
// }
request.Content = content;
HttpResponseMessage response = null;
try
{
response = httpClient.SendAsync(request).Result;
}
catch (Exception z)
{
object x = 20;
}
// txtLastRequestUrl.Text = uri.ToString();
if (!response.IsSuccessStatusCode)
{
// remark:response.ReasonPhrase is encoded at server for supporting persian
string reasonPhrase = System.Web.HttpUtility.UrlDecode(response.ReasonPhrase);
// txtLastResponseMessage = String.Format("{0}:{1} Details {2}", response.StatusCode, reasonPhrase, response.Content.ReadAsStringAsync.Result)
}
else
{
int x =0;
// txtLastResponseMessage = "Successful"
}
httpClient.Dispose();
return response;
}
}
这是我的Windows控制台应用程序:
static void Main(string[] args)
{
Test s = new ConsoleApplication6.Test();
StreamReader r = new StreamReader("1.json");
string json = r.ReadToEnd();
string username = "xxxxxxx";
string password = "yyyyyyyy";
s.GetDataFromWebAPI_AccountNO(json, 1, "Address", "Full Add", username, password);
}
public class Test
{
string authenticationToken;
private HttpResponseMessage SendRequest_getDataAccountNumberList(string userNameApi, string passwordApi, HttpMethod httpMethod, string strUri, HttpContent content = null)
{
System.Net.Http.HttpClient httpClient = new HttpClient();
// Warning!!! Optional parameters not supported
Uri uri;
uri = new Uri(strUri);
HttpRequestMessage request = new HttpRequestMessage(httpMethod, uri);
if (!string.IsNullOrEmpty(authenticationToken))
{
request.Headers.Add("authenticationtoken", authenticationToken);
}
// if(uriScheme == Uri.UriSchemeHttps)
// {
request.Headers.Add("username", userNameApi);
request.Headers.Add("password", passwordApi);
// }
request.Content = content;
HttpResponseMessage response = null;
try
{
response = httpClient.SendAsync(request).Result;
}
catch (Exception z)
{
object x = 20;
}
// txtLastRequestUrl.Text = uri.ToString();
if (!response.IsSuccessStatusCode)
{
// remark:response.ReasonPhrase is encoded at server for supporting persian
string reasonPhrase = System.Web.HttpUtility.UrlDecode(response.ReasonPhrase);
// txtLastResponseMessage = String.Format("{0}:{1} Details {2}", response.StatusCode, reasonPhrase, response.Content.ReadAsStringAsync.Result)
}
else
{
int x = 0;
// txtLastResponseMessage = "Successful"
}
httpClient.Dispose();
return response;
}
public string GetDataFromWebAPI_AccountNO(string bsIdJsonList, int InsuranceID, string MainServerUrl, string FullUrl, string UserName, string Password)
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
List<AccountNoToGet> accounts = new List<AccountNoToGet>();
accounts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AccountNoToGet>>(bsIdJsonList);
authenticationToken = "";
string txtServerUrlFinal = "";
if ((MainServerUrl.EndsWith("/") != true))
{
txtServerUrlFinal = "/";
}
// ''''''''''''''' Authenticate
HttpResponseMessage responseAuthenticate = null;
responseAuthenticate = SendRequest_authenticate(UserName, Password, HttpMethod.Post, (MainServerUrl
+ (txtServerUrlFinal + "api/EITAuthentication/Login")), null);
if (responseAuthenticate.IsSuccessStatusCode)
{
authenticationToken = responseAuthenticate.Headers.GetValues("authenticationToken").FirstOrDefault();
}
int i = 0;
responseAuthenticate.Dispose();
// ''''''''''''''' GetData
foreach (var item in accounts)
{
i++;
string txtContentBody = ("{bsId: " + item.Bid.ToString() + "}");
HttpMethod method = HttpMethod.Post;
HttpResponseMessage responseGetData = null;
try
{
responseGetData = SendRequest_getDataAccountNumberList(UserName, Password, method, FullUrl, new StringContent(txtContentBody, Encoding.UTF8, "application/json"));
}
catch (Exception ex)
{
object x = 50;
}
if (responseGetData.IsSuccessStatusCode)
{
string ACCFinal = "";
var parsed = JObject.Parse((responseGetData.Content.ReadAsStringAsync().Result));
AccountNoInformationReturn accountNoInformationReturn = new AccountNoInformationReturn();
accountNoInformationReturn.BsId = parsed.SelectToken("Data.BsId").ToString();
accountNoInformationReturn.CmnId = parsed.SelectToken("Data.CmnId").ToString();
accountNoInformationReturn.AccNo = parsed.SelectToken("Data.AccNo").ToString();
accountNoInformationReturn.CardNo = parsed.SelectToken("Data.CardNo").ToString();
accountNoInformationReturn.ShebaAcc = parsed.SelectToken("Data.ShebaAcc ").ToString();
accountNoInformationReturn.ErrMsg = parsed.SelectToken("Data.ErrMsg").ToString();
if (accountNoInformationReturn.ErrMsg != "")
{
ACCFinal = "-";
}
else if (accountNoInformationReturn.AccNo == "" & accountNoInformationReturn.CardNo == "" & accountNoInformationReturn.ShebaAcc == "")
{
ACCFinal = "-";
}
else
{
if (accountNoInformationReturn.CardNo.Length != 0) ACCFinal = accountNoInformationReturn.CardNo;
else if (accountNoInformationReturn.AccNo.Length != 0) ACCFinal = accountNoInformationReturn.AccNo;
else if (accountNoInformationReturn.ShebaAcc.Length != 0) ACCFinal = accountNoInformationReturn.ShebaAcc;
var change = (from lst in accounts
where lst.Bid == item.Bid
select lst).FirstOrDefault();
if (change != null) change.ACC = ACCFinal;
}
}
else
{
return JsonConvert.SerializeObject(accounts);
}
}
return JsonConvert.SerializeObject(accounts);
}
private HttpResponseMessage SendRequest_authenticate(string userNameApi, string passwordApi, HttpMethod httpMethod, string strUri, HttpContent content = null)
{
System.Net.Http.HttpClient httpClient = new HttpClient();
// Warning!!! Optional parameters not supported
Uri uri;
uri = new Uri(strUri);
HttpRequestMessage request = new HttpRequestMessage(httpMethod, uri);
if (!string.IsNullOrEmpty(authenticationToken))
{
request.Headers.Add("authenticationtoken", authenticationToken);
}
// if(uriScheme == Uri.UriSchemeHttps)
// {
request.Headers.Add("username", userNameApi);
request.Headers.Add("password", passwordApi);
// }
request.Content = content;
HttpResponseMessage response = null;
try
{
response = httpClient.SendAsync(request).Result;
}
catch (Exception z)
{
object x = 20;
}
// txtLastRequestUrl.Text = uri.ToString();
if (!response.IsSuccessStatusCode)
{
// remark:response.ReasonPhrase is encoded at server for supporting persian
string reasonPhrase = System.Web.HttpUtility.UrlDecode(response.ReasonPhrase);
// txtLastResponseMessage = String.Format("{0}:{1} Details {2}", response.StatusCode, reasonPhrase, response.Content.ReadAsStringAsync.Result)
}
else
{
// txtLastResponseMessage = "Successful"
}
httpClient.Dispose();
return response;
}
}
那是完全相同但第一个在某些itterate中返回Autentication错误!!