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

本文关键字:引用 异常 API 参数 调用 Web | 更新日期: 2023-09-27 17:51:05

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

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

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

尝试在您的请求中像这样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);
}

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