请教哪位可以告知:解引用可能出现空引用是什么意思?怎么处理呢?
代码及截图如下:
string? sIP = Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(sIP)) sIP = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
非常感谢感谢~
使用null条件运算符【?.】,当RemoteIpAddress为null时直接返回null,不会调用后面的代码导致null引用报错。
if (string.IsNullOrEmpty(sIP)) sIP = Request.HttpContext.Connection.RemoteIpAddress?
.MapToIPv4().ToString();
按照下面的也行
if (string.IsNullOrEmpty(sIP)&&Request.HttpContext.Connection.RemoteIpAddress!=null) sIP = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
Request.HttpContext.Connection.RemoteIpAddress结果可能为空,会导致异常,需要对结果进行非空判断。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!