我有一個網頁,我正在嘗試呼叫 Web 服務,并且在呼叫時它會跳過該程序。
這就是我所指的...
當我在客戶輸入他們的支票資訊后呼叫此方法時:
public CheckInfo SubmitCheck(CheckInfo checkInfo)
{
try
{
var check = new Check();
check.account_number = checkInfo.CheckAccountNumber;
check.transit_number = checkInfo.CheckRoutingNumber;
check.amount = checkInfo.Amount.ToString();
check.check_number = checkInfo.CheckNumber;
check.bill_to_city = checkInfo.City;
check.bill_to_country = "US";
check.bill_to_postal_code = checkInfo.Zip;
check.bill_to_street = checkInfo.Street;
check.bill_to_state = checkInfo.State;
check.name_on_check = checkInfo.NameOnCheck;
check.transaction_type = "sale";
check.account_type = checkInfo.AccountType;
check.check_type = checkInfo.CheckType;
var ent = new SuburbanPortalEntities();
var gatewaySettings = (from x in ent.GatewayUsers
where x.TokenId == CurrentCustomerSession.Current.TokenId &&
x.Gateway.Name == "DirectAch2"
select x).FirstOrDefault();
var credentials = new Authentication();
credentials.password = gatewaySettings.Password;
credentials.username = gatewaySettings.UserName;
var response = Process.SubmitCheck(credentials, check).Result;
呼叫私有類的公共類:
public static async Task<Response> SubmitCheck(Authentication authentication, Check check)
{
return await Submit(authentication, check, PaymentTypes.Check);
}
提交檢查方法:
private static async Task<Response> Submit(Authentication authentication, Object payment, PaymentTypes paymentType)
{
var resp = new Response();
try
{
var client = new HttpClient();
var bodyjson = JsonConvert.SerializeObject(authentication);
var bodycontent = new StringContent(bodyjson, Encoding.UTF8, "application/json");
var authenticationPost =
await client.PostAsync("https://someplace.com/api/v2/Identity", bodycontent);
var bodyResponseJson = await authenticationPost.Content.ReadAsStringAsync();
當我到達這一行時,它只是從方法中回傳,并且不會繼續執行任何操作,就好像我從未執行過此方法一樣。
var authenticationPost =
await client.PostAsync("https://someplace.com/api/v2/Identity", bodycontent);
此行之后沒有其他代碼被執行。它只是停止,網頁再次可用。我將方法包裹在 try catch 中,但 catch 沒有捕獲任何東西。
我對這個姿勢不知所措,有什么建議嗎?
編輯#1
我按照建議將線包裹在 try catch 中。
try
{
authenticationPost =
await client.PostAsync("https://someplace.com/api/v2/Identity", bodycontent);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
它退出了 try/catch,之后不再執行任何代碼。沒有捕獲到例外,什么都沒有,它只是運行該行并離開該方法。
uj5u.com熱心網友回復:
這是你的問題:
var response = Process.SubmitCheck(credentials, check).Result;
不要阻塞異步代碼,正如我在博客中所描述的那樣。async對于那些剛接觸/的人來說,這是一個常見的錯誤await。而不是Result,使用await:
public async Task<CheckInfo> SubmitCheck(CheckInfo checkInfo)
{
...
var response = await Process.SubmitCheck(credentials, check);
請注意,您隨后需要await呼叫SubmitCheck,依此類推。async一路走來。
旁注:我建議在方法名稱上使用標準的*Async后綴模式;它在代碼中更清楚地表明它們的回傳值需要被await編輯:
public async Task<CheckInfo> SubmitCheckAsync(CheckInfo checkInfo)
{
...
var response = await Process.SubmitCheckAsync(credentials, check);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428793.html
標籤:C# asp.net-mvc 后同步
上一篇:Ajax向控制器發送空引數
