gpt4 book ai didi

c# - RouteData.Values 查询字符串不存在时返回 NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 14:00:33 25 4
gpt4 key购买 nike

如果在使用 URL 路由时查询字符串中不存在以下语句,我将收到以下语句的 null 异常错误,我该如何处理以下语句的 NullReferenceException

string lang = RouteData.Values["Language"].ToString();

错误详情

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

异常详情:

System.NullReferenceException: Object reference not set to an instance of an object.

最佳答案

您收到此异常是因为 RouteDate.Values["Language"] 为空并且您正在对其应用实例方法 .ToString。
只需添加一个 if 来检查 null

string lang="";
if(RouteData.Values["Language"] != null)
lang = RouteData.Values["Language"].ToString();

关于c# - RouteData.Values 查询字符串不存在时返回 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10533437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com