【发布时间】:2021-12-13 09:36:46
【问题描述】:
我正在尝试使用从 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;
}
}
【问题讨论】:
-
仅供参考:
throw ex;几乎不是您想要使用的东西。此外,使用 try-catch 只是为了重新抛出而没有任何逻辑(甚至没有记录!)是没有意义的,只需完全删除 try-catch。但是,Controller 操作不应引发异常,而应返回内部服务器错误 -
对我来说,你的代码只做了一个发送http请求和接收响应的过程,不用担心是否发生异常以及如何处理,你可以关注@987654324 @ 本身。
标签: c# facebook asp.net-core dotnet-httpclient