I am trying to get value from the HttpContext
with a key Correlation-Context
, but I am not sure why I am getting the error while trying to use the variable json
.
internal static CorrelationContext GetCorrelationContext(this IHttpContextAccessor accessor)
{
return accessor.HttpContext?.Request.Headers.TryGetValue("Correlation-Context", out var json) is true
? JsonConvert.DeserializeObject<CorrelationContext>(json.FirstOrDefault())
: null;
}
I am getting the error as:
Error CS0165 Use of unassigned local variable 'json'
I am using the target framework of net 5.0
Although it's obvious to us, I think it's a bit too complicated for the compiler to understand that if
HttpContext
isnull
then the statement will evaluate tofalse
.You can fix your method by moving adding a null check and not using
?.
: