我正在嘗試使用從 Facebook 收到的代碼從 Facebook 的圖形 API 接收訪問令牌。這是我第一次在 .NET CORE 中使用 API。代碼似乎作業正常,但是我不確定我是否以正確的方式處理回應和捕獲例外。雖然我可以使用 TRY CATCH 仍然覺得不太舒服。我想讓這個方法盡可能健壯。
非常感謝您的幫助。
處理類
public class FacebookService : IFacebookService
{
private readonly HttpClient _httpClient;
private readonly IConfiguration configuration;
public FacebookService(HttpClient httpClient, IConfiguration iConfig)
{
_httpClient = httpClient;
configuration = iConfig;
}
public async Task<string> GetShortLiveToken(string code)
{
try
{
string appId = configuration.GetSection("FacebookApp").GetSection("AppID").Value;
string appSecret = configuration.GetSection("FacebookApp").GetSection("AppSecret").Value;
var getTokenUri = $"oauth/access_token?client_id={appId}&client_secret={appSecret}&code={code}&redirect_uri=https://localhost:44373/Home/HandleFbAccess";
var response = await _httpClient.GetAsync(getTokenUri);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return response.ReasonPhrase;
}
}
catch(Exception ex)
{
throw ex;
}
}
public async Task<string> GetLongLiveToken(string shortlivedtoken)
{
throw new NotImplementedException();
}
}
呼叫方法
public async Task<IActionResult> HandleFbAccess(string code, string granted_scopes)
{
try
{
var result = await _facebookService.GetShortLiveToken(code);
// more things to do here
//.....
return View("Index");
}
catch(Exception ex)
{
throw ex;
}
}
uj5u.com熱心網友回復:
try{}catch(Exception ex){}當您的代碼突發例外時起作用,例如nullpointexception,但您現在擔心的是httpclient send request,您應該知道此方法只能拋出這些例外,并且所有這些例外都與 facebook api 無關。

我對你的場景的想法是try catch在這里繼續使用,但你需要根據例外型別設定操作catch{}并在此處撰寫自定義邏輯代碼,以處理 http 回應,例如 404,400,503 問題等:
if (response.IsSuccessStatusCode){
return await response.Content.ReadAsStringAsync();
}else{
return response.ReasonPhrase;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/383840.html
標籤:C# Facebook asp.net核心 dotnet-httpclient
上一篇:c#中的動態屬性取決于列舉值
