Web API参数调用中的空引用异常

时间:2015-05-28 18:33:20

标签: c# asp.net-web-api

我的Web API在

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

  return leadRepository.SearchLead(searchCriteria);
}

我正在调用

http://localhost:52388/LeadAPI/SearchLead

但我得到NULL引用异常。

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

我犯了什么错误?

邮差

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

错误

{
    "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()"
}

1 个答案:

答案 0 :(得分:1)

您的控制器方法需要您在请求中传递对象的JSON或XML表示,以便它可以使用它。您也可以在参数类型之前使用[FromUri]注释将其传递给Uri。

在您的请求中尝试POST这样的JSON:

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

或者,您可以像这样编辑Get方法:

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

并发送这样的请求:

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

修改

正如我已经说过的,您正在尝试将对象POST到控制器,因此将您的方法更改为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);
}

请注意,您应该使用上面的方法中的业务逻辑,我只是​​为了快速测试而展示了开箱即用的示例。