1

I am building a new WebAPI layer for a legacy ASP.NET WebForms application. I am trying to get my query parameters to be used with an end-point, and I cannot for the life of me figure out why when I do an evaluation on the argument variable to check to see if first_name.Equals(null) why it's not properly being flagged true, and instead throws the below exception:

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

first_name was null.

Exception thrown when this is the request:

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

Exception is NOT thrown when this is the request:

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

I get that by default the value passed to the end-point will be null, but even with assigning a default value, it is still not getting flagged null as TRUE.

Here is my end-point:

[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));
}

Here is my Routing information in the Global.ascx.cs:

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

Things I have tried:

  • Setting the following method attribute [Route("api/v1/person/{first_name?}/{last_name?}")]

  • Setting the [FromUri] attribute with the method arguments

Nothing has worked so far.

Jason Ayer
  • 621
  • 1
  • 10
  • 20
  • you use `Equals` on an object that is null, hence the nullreference. – VDWWD Oct 11 '19 at 14:18
  • @VDWWD I JUST realized what I was doing wrong and discovered this. Side question, is it by design that when no value is passed that it won't be instantiated with the default value as set in the argument? – Jason Ayer Oct 11 '19 at 14:27
  • You technically are passing a value, but it's null, so it overrides your default. Remove `first_name=` and see what happens. – mxmissile Oct 11 '19 at 14:31

1 Answers1

0

Turns out the exception is valid and my evaluation logic is wrong.

Changing if (!first_name.Equals(null)) to if (first_name != null) now properly evaluates to TRUE.

Jason Ayer
  • 621
  • 1
  • 10
  • 20