asp.net-core - 应用程序的异步调用开始返回 Null
问题描述
当您导航到主页时,我有一个调用检索数据库中的所有类别。这个想法是索引页面动态显示类别列表。类别是通过使用 EF .Net Core 搭建将类别插入数据库的代码来放置的——这就是数据库的样子。
https://gyazo.com/c407f03ae60a82c6fa6f9ee12105089d
编辑:获取类别:
[AllowAnonymous]
public async Task<List<Category>> GetCategoriesFromDb()
{
return await _context.Categories.Where(x => x.ParentId == 0).ToListAsync();
}
它抛出这个错误:
https://gyazo.com/7e27dda9ff57b6e28b58b563abd05767
ArgumentNullException: Value cannot be null.
Parameter name: source
System.Linq.Enumerable.Count<TSource>(IEnumerable<TSource> source)
AspNetCore.Views_Home__categories.ExecuteAsync() in _categories.cshtml
+
@if (Model.Count() > 0)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage
page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page,
ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) =
AspNetCore.Views_Home_Index.ExecuteAsync() in Index.cshtml
+
<partial name="_categories" , for="Categories" />
似乎在随后导航到页面时(字面意思是刷新一次),错误就消失了。
这是失败的控制器:
https://gyazo.com/ee6db603cde49a7b704b200e7e5fa2dc
// Model stores an IEnumerable of Products and Categories to be used with the two partial views.
Index myModel = new Index();
myModel.Categories = new List<Category>();
myModel.Products = new List<Product>();
myModel.Categories = await GetCategories();
这是有问题的代码和视图:
https://gyazo.com/634b6867601fc582836e284cdacb0ca3
@{
@model List<Category>
}
<div>
@if (Model.Count() > 0)
{
<a class="btn btn-secondary" href="~/Home/Index/" style="margin-bottom:10px;">All</a>
@foreach (var item in Model)
{
<a class="btn btn-secondary" href="~/Home/Index?Category=@item.Name&Zip=@ViewBag.Zip" style="margin-bottom:10px;">@item.Name</a>
}
}
else
{
<a class="btn btn-secondary" href="~/Home/Index/" style="margin-bottom:10px;">All</a>
}
</div>
这是视图模型:
https://gyazo.com/e5053f6827d2198742279eb37071c733
namespace Market.Views.Home
{
public class Index
{
public List<Product> Products { get; set; }
public List<Category> Categories { get; set; }
}
如果我再次导航到该页面,错误就会消失。恐怕这是我的应用程序返回 500 错误 0.4% 的原因。
我尝试将其从 IEnumerable 更改为 List - 但我实际上并不知道如何解决问题。当类别列表为空时,我似乎需要处理,但我希望视图根本不会崩溃并等到所有类别都被检索到。
我可以说这是因为当 Razor 视图点击 if 语句检查是否有类别时,类别列表为空。我认为,它应该简单地重试直到有类别,但我不确定。
编辑:经过进一步检查,根据 Azure,我的 SQL 数据库服务器上发生了错误。它带有这个异常,这似乎与我在本地遇到的问题有关。
System.NullReferenceException: Object reference not set to an instance of an object.
at Market.Controllers.HomeController.GetGeoProducts(Nullable`1 Distance, String productSearch, String Zip, String Category) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 162
at Market.Controllers.HomeController.Index(String Category, Double Distance, String productSearch, String Zip, String sortOrder, String currentFilter, Nullable`1 pageNumber) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 80
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at System.Threading.Tasks.ValueTask`1.get_Result()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
解决方案
感谢你们的帮助——这最终成为了伐木方面的重要一课。
我更改了代码以获取类别以创建一个预填充的 SelectList 而不是从数据库中检索它。
@{
var Categories = new List<Category>(){
//new Category
//{
// CategoryId = 1,
// ParentId = 0,
// Name = "All",
// ParentCategory = null
//},
new Category
{
CategoryId = 2,
ParentId = 0,
Name = "Electronics",
ParentCategory = null
},
new Category
{
CategoryId = 3,
ParentId = 0,
Name = "Furniture",
ParentCategory = null
},
new Category
{
CategoryId = 4,
ParentId = 0,
Name = "Clothing",
ParentCategory = null
},
new Category
{
CategoryId = 5,
ParentId = 0,
Name = "Shoes",
ParentCategory = null
},
new Category
{
CategoryId = 6,
ParentId = 0,
Name = "Video Games",
ParentCategory = null
},
new Category
{
CategoryId = 7,
ParentId = 0,
Name = "Books",
ParentCategory = null
},
new Category
{
CategoryId = 8,
ParentId = 0,
Name = "Tools",
ParentCategory = null
},
new Category
{
CategoryId = 9,
ParentId = 0,
Name = "Vehicles",
ParentCategory = null
},
new Category
{
CategoryId = 10,
ParentId = 0,
Name = "Free",
ParentCategory = null
},
new Category
{
CategoryId = 11,
ParentId = 0,
Name = "Jewelry",
ParentCategory = null
},
new Category
{
CategoryId = 12,
ParentId = 0,
Name = "Crafts",
ParentCategory = null
},
new Category
{
CategoryId = 13,
ParentId = 0,
Name = "Crafts",
ParentCategory = null
},
new Category
{
CategoryId = 14,
ParentId = 0,
Name = "Appliances",
ParentCategory = null
},
new Category
{
CategoryId = 15,
ParentId = 0,
Name = "Health",
ParentCategory = null
},
new Category
{
CategoryId = 16,
ParentId = 0,
Name = "Tickets",
ParentCategory = null
},
new Category
{
CategoryId = 17,
ParentId = 0,
Name = "Services",
ParentCategory = null
},
new Category
{
CategoryId = 18,
ParentId = 0,
Name = "Home & Garden",
ParentCategory = null
},
new Category
{
CategoryId = 19,
ParentId = 0,
Name = "Collectibles",
ParentCategory = null
}
};
但是错误仍然被抛出 - 所以我在添加 NLog 后检查了日志:
2019-05-06 12:09:56.6564|ERROR|Market.Controllers.HomeController|MaxMind.GeoIP2.Exceptions.AddressNotFoundException: The address ::1 is not in the database.
at MaxMind.GeoIP2.DatabaseReader.Execute[T](String ipStr, IPAddress ipAddress, String type, Boolean throwOnNullResponse)
at MaxMind.GeoIP2.DatabaseReader.City(IPAddress ipAddress)
at Market.Controllers.HomeController.GetGeoProducts(Nullable`1 Distance, String productSearch, String Zip, String Category) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 169
at Market.Controllers.HomeController.Index(String Category, Nullable`1 Distance, String productSearch, String Zip, String sortOrder, String currentFilter, Nullable`1 pageNumber) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 85
2019-05-06 12:12:07.8714|ERROR|Market.Controllers.HomeController|MaxMind.GeoIP2.Exceptions.AddressNotFoundException: The address ::1 is not in the database.
at MaxMind.GeoIP2.DatabaseReader.Execute[T](String ipStr, IPAddress ipAddress, String type, Boolean throwOnNullResponse)
at MaxMind.GeoIP2.DatabaseReader.City(IPAddress ipAddress)
at Market.Controllers.HomeController.GetGeoProducts(Nullable`1 Distance, String productSearch, String Zip, String Category) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 169
at Market.Controllers.HomeController.Index(String Category, Nullable`1 Distance, String productSearch, String Zip, String sortOrder, String currentFilter, Nullable`1 pageNumber) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 85
2019-05-06 12:21:50.0824|ERROR|Market.Controllers.HomeController|MaxMind.GeoIP2.Exceptions.AddressNotFoundException: The address ::1 is not in the database.
at MaxMind.GeoIP2.DatabaseReader.Execute[T](String ipStr, IPAddress ipAddress, String type, Boolean throwOnNullResponse)
at MaxMind.GeoIP2.DatabaseReader.City(IPAddress ipAddress)
at Market.Controllers.HomeController.GetGeoProducts(Nullable`1 Distance, String productSearch, String Zip, String Category) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 169
at Market.Controllers.HomeController.Index(String Category, Nullable`1 Distance, String productSearch, String Zip, String sortOrder, String currentFilter, Nullable`1 pageNumber) in C:\Users\nvn\source\repos\market\Market.Core\Market.Core\Controllers\HomeController.cs:line 85
出于某种原因,实际错误——在 GeoIP DB 中找不到 IP 地址——被隐藏在 prod 中抛出的堆栈跟踪中。不太清楚为什么,但要么是使用了我们在免费版本中没有的 IP 范围的人,要么是出现了一些环回错误,就像我们在开发模式下调试时一样。
反正我是这样处理的——
// Determine IP address of request.
var ipAddress = HttpContext.Connection.RemoteIpAddress;
try
{
// Grab the city if it's not null
var city = reader.City(ipAddress);
ViewBag.Zip = city.Postal.Code;
ViewBag.CurrentDistance = Distance;
}
catch(AddressNotFoundException e)
{
logger.Warn(e.ToString());
// Grab the city if it's not null
var city = reader.City("insert a random IP here");
ViewBag.Zip = city.Postal.Code;
ViewBag.CurrentDistance = Distance;
}
谢谢大家的帮助。
推荐阅读
- javascript - 无法设置未定义 4 的属性“大小”
- android - Rn 声音问题:在后台播放但在通话时停止音乐
- pandas - 如何从连续列值中提取最大和最小时间?
- python - python:如何从列表中打印单独的行?
- django - 从视图中检索 form.errors 并打印到控制台
- reactjs - 无法从 recompose 更改状态 withStateHandlers
- jquery - jquery选择器不返回数组
- haskell - 如何在 Haskell 中使用类型的派生 Generic 实例从有限离散类型的值到 (Finite n) 并返回?
- angular6 - Angular6如何继续添加带有选定值的下拉列表
- c - IOCTL 可以用于向驱动程序发送自定义输入吗