Skip to main content
 首页 » 编程设计

c#之你调用的对象是空的。使用非空对象。

2024年02月06日12artech

好吧,我遇到了这个让我发疯的问题,我正在搜索一个网站,它在我的机器上运行良好,但是当我将它上传到 gearhost 时,它就出现了这个错误:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

Line 43: @if (Model != null)
Line 44: {
Line 45: if (Model.Any())
Line 46: {

错误出现在第 45 行,尽管我确定我知道它不是 null 并且它是 IEnumerable。

我在 Razor 中的模型声明如下:

@model IEnumerable<Posada>  

如果我发送一个空搜索,这确实有效,但当我使用返回行的字符串或其他不返回任何行的字符串时则无效。

在我的 Controller 中,我只返回一个 IEnumerable 并将其用作模型。

 IEnumerable<Posada> posadas = unitOfWork.PosadaRepository.Get(includeProperties: "Estado,Lugar") 
                .Where(p => p.Nombre.ToLowerInvariant().Contains(query) || 
                            p.Estado.Nombre.ToLowerInvariant().Contains(query) || 
                            p.Lugar.Nombre.ToLowerInvariant().Contains(query)) 
 
                .OrderBy(p => p.Id) 
                .Skip((page - 1)*pagingInfo.ItemsPerPage) 
                .Take(pagingInfo.ItemsPerPage); 

请您参考如下方法:

似乎 NullReferenceException 发生在您枚举 IEnumerable 时(当您执行 Any() 时)。 IEnumerable 不为空,然后很可能出现 NullReferenceException:

p.Nombre.ToLowerInvariant() 
p.Estado.Nombre.ToLowerInvariant() 
p.Lugar.Nombre.ToLowerInvariant() 
pagingInfo.ItemsPerPage