获取token时如何解析"possible System.NullReferenceException"
How to resolve "possible System.NullReferenceException" while acquiring token
我正在按照 "Azure-Sample" 中提供的示例代码获取令牌以调用 Microsoft Graph Api。但是 Resharper 建议 "Possible System.NullReferenceException" in await app.AcquireTokenForClient(scopes) .ExecuteAsync();如何解决 NullReference 异常?
克隆代码并查看 "Possible System.NullReferenceException"
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token acquired");
Console.ResetColor();
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be of the form "https://resourceurl/.default"
// Mitigation: change the scope to be as expected
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Scope provided is not supported");
Console.ResetColor();
}
Resharper 建议 "Possible System.NullReferenceException",知道如何解决吗?
处理这种情况的方法是检查是否为空,如果是则引发异常。
假设 app
是您的方法的输入变量:
void Foo(IApp app) //just using IApp as an example.
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var result = app.Bar(); //no possible null ref here.
}
"Pessimistic" 值分析模式在 ReSharper 中启用,它认为一切都可以是 "null",除非明确检查是否为 null 或使用 "NotNull" 或 "ContractAnnotation" 属性进行注释.
处理这种情况的一些选项:
- 为 "AcquireTokenForClient"
提供外部注释
将"app.AcquireTokenForClientAsync(scopes)"提取到局部变量并检查它是否为空:
var task = app.AcquireTokenForClientAsync(作用域);
如果(任务== null)抛出新的异常();
结果=等待任务;
启用"Optimistic"值分析模式
我正在按照 "Azure-Sample" 中提供的示例代码获取令牌以调用 Microsoft Graph Api。但是 Resharper 建议 "Possible System.NullReferenceException" in await app.AcquireTokenForClient(scopes) .ExecuteAsync();如何解决 NullReference 异常?
克隆代码并查看 "Possible System.NullReferenceException"
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token acquired");
Console.ResetColor();
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be of the form "https://resourceurl/.default"
// Mitigation: change the scope to be as expected
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Scope provided is not supported");
Console.ResetColor();
}
Resharper 建议 "Possible System.NullReferenceException",知道如何解决吗?
处理这种情况的方法是检查是否为空,如果是则引发异常。
假设 app
是您的方法的输入变量:
void Foo(IApp app) //just using IApp as an example.
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var result = app.Bar(); //no possible null ref here.
}
"Pessimistic" 值分析模式在 ReSharper 中启用,它认为一切都可以是 "null",除非明确检查是否为 null 或使用 "NotNull" 或 "ContractAnnotation" 属性进行注释. 处理这种情况的一些选项:
- 为 "AcquireTokenForClient" 提供外部注释
将"app.AcquireTokenForClientAsync(scopes)"提取到局部变量并检查它是否为空:
var task = app.AcquireTokenForClientAsync(作用域); 如果(任务== null)抛出新的异常(); 结果=等待任务;
启用"Optimistic"值分析模式