priyanka.sarkar
priyanka.sarkar

Reputation: 26498

Null Reference Exception in Web API parameter calling

My Web API is as under

[HttpGet]
[Route("SearchLead")]
public IEnumerable<LeadSearchResult> SearchLead1(LeadSearchCriteria searchCriteria)
{

  return leadRepository.SearchLead(searchCriteria);
}

I am invoking as

http://localhost:52388/LeadAPI/SearchLead

But I am getting NULL Reference exception.

public class LeadSearchCriteria
    {
        LeadSearchCriteria() { }
        public int ProductID { get; set; }
        public int ProductProgramId { get; set; }        
    }

What mistake I am making?

Postman

{
  "ProductID": 1,
  "ProductProgramId": 1
}

ERROR

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "Object reference not set to an instance of an object.",
    "ExceptionType": "System.NullReferenceException",
    "StackTrace": "   at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}

Upvotes: 2

Views: 8984

Answers (1)

mwilczynski
mwilczynski

Reputation: 3082

Your controller method needs you to pass JSON or XML representation of your object in request so that it can use it. You can also pass it through Uri with [FromUri] annotation before parameter type.

Try POSTing JSON like this in your request:

{
 "ProductID": 1,
 "ProductProgramID": 2
}

Alternatively you can edit your Get method like this:

[HttpGet]
[Route("SearchLead")]
public IEnumerable<LeadSearchResult> SearchLead1(int productID, int productProgramID)
{
  //edit SearchLead to make use of integer params
  return leadRepository.SearchLead(productID, productProgramID);
}

And send request like this:

http://myapi:12345/SearchLead?productID=1&productProgramID=2

Edit:

As I already said, you are trying to POST object to controller, so change your method to HttpPost:

[HttpPost]
[Route("SearchLead")]
public IEnumerable<LeadSearchResult> PostCriteria([FromBody]LeadSearchCriteria criteria)
{
    List<LeadSearchResult> list = new List<LeadSearchResult>() { new LeadSearchResult { ProductID = 1, Result = 12 }, new LeadSearchResult { ProductID = 2, Result = 22 } };
    return list.Where(x => x.ProductID == criteria.ProductID);
}

Please note that you should use your business logic inside method above, I just shown out of the box example for fast testing purposes.

Upvotes: 2

Related Questions