【问题标题】:Why is first_name not properly being evaluated as null?为什么 first_name 没有被正确地评估为 null?
【发布时间】:2019-10-11 14:00:09
【问题描述】:

我正在为旧的 ASP.NET WebForms 应用程序构建一个新的 WebAPI 层。我试图让我的查询参数与端点一起使用,但我一生都无法弄清楚为什么当我对参数变量进行评估以检查 first_name.Equals(null) 是否不正确时标记为 true,而是抛出以下异常:

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

first_name was null.

当这是请求时抛出异常:

http://localhost/api/v1/person?first_name=

当这是请求时,NOT抛出异常:

http://localhost/api/v1/person?first_name=John

我知道默认情况下传递给端点的值将为空,但即使分配了默认值,它仍然没有被标记为 nullTRUE

这是我的终点:

[HttpGet]
public void Get(string first_name = "", string last_name = "")
{
    string firstName = String.Empty;
    if (!first_name.Equals(null))  // Here is where the ObjectReferenceNull exception is thrown
        firstName = first_name;

    ...

    ApiResponse.Json(new JsonResource(data, links));
}

这是我在 Global.ascx.cs 中的路由信息​​:

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/v1/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
);

我尝试过的事情:

  • 设置如下方法属性[Route("api/v1/person/{first_name?}/{last_name?}")]

  • 使用方法参数设置[FromUri] 属性

到目前为止没有任何效果。

【问题讨论】:

  • 你在一个为空的对象上使用Equals,因此是空引用。
  • @VDWWD 我刚刚意识到我做错了什么并发现了这一点。附带的问题,是否设计为在没有传递任何值时不会使用参数中设置的默认值对其进行实例化?
  • 从技术上讲,您正在传递一个值,但它是 null,因此它会覆盖您的默认值。删除first_name= 看看会发生什么。

标签: asp.net webforms asp.net-web-api2


【解决方案1】:

原来异常是有效的,而我的评估逻辑是错误的。

if (!first_name.Equals(null)) 更改为 if (first_name != null) 现在可以正确评估为 TRUE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2022-08-10
    • 2021-03-22
    • 2020-08-15
    • 2023-03-20
    相关资源
    最近更新 更多