IFeatureCollection 已被处置。对象名称:'Collection'。从控制器到视图
IFeatureCollection has been disposed. Object name: 'Collection'. going from controller to view
我对这一切都是陌生的,并且正处于制作此 Web 应用程序的早期阶段。这仅供我个人使用。我正在尝试在视图中显示网络 api 调用的结果。 api 调用工作正常。我可以看到数据从服务返回并被放置在 DTO 中。它从服务到控制器,但我不确定为什么每次我尝试将数据从控制器发送到视图时,我都会遇到相同的异常:
IFeatureCollection has been disposed. Object name: 'Collection'.
谁能告诉我这是什么意思,我该如何解决这个问题?
这是我的 Startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("mapQUrl", client => { client.BaseAddress = new Uri("https://www.mapquestapi.com/geocoding/v1/address?"); });
services.AddHttpClient("climaUrl", client => { client.BaseAddress = new Uri("https://api.climacell.co/v3/weather/nowcast?"); });
services.AddControllersWithViews();
services.AddScoped<IServices, Services>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
这是我的服务:
public async Task<List<ClimaCellDto>> GetTemp(MapQuestFlatDto loc)
{
List<ClimaCellDto> dataObjects = new List<ClimaCellDto>();
var client = _clientFactory.CreateClient("climaUrl");
string attr = "unit_system=us×tep=5&start_time=now&fields=temp&";
var url = client.BaseAddress + attr + climaUrlParameters;
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url); // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var strContent = await response.Content.ReadAsStringAsync(); //Make sure to add a reference to System.Net.Http.Formatting.dll
dataObjects = JsonConvert.DeserializeObject<List<ClimaCellDto>>(strContent);
return dataObjects;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
return dataObjects;
}
这是从服务接收数据并将其发送到视图的控制器方法:
[HttpPost]
public async void getLoc ([FromBody]ZipDto obj)
{
var zip = Int32.Parse(obj.zip);
var location = await _services.GetLatLng(zip);
var climate = await _services.GetTemp(location);
ShowResults(climate);
}
public IActionResult ShowResults(List<ClimaCellDto> data)
{
try
{
return View(data);
}
catch (Exception ex)
{
throw ex;
}
}
这是视图:
@model IEnumerable<Weather_web_app.DTOs.ClimaCellDto>
@{
ViewData["Title"] = "ShowResults";
}
<h1>ShowResults</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.lat)
</th>
<th>
@Html.DisplayNameFor(model => model.lon)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.observation_time.value)
</td>
<td>
@Html.DisplayFor(modelItem => item.temp.value)
</td>
</tr>
}
</tbody>
</table>
这是调用堆栈:
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ThrowContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.Fetch[TFeature,TState](TFeature& cached, TState state, Func`2 factory)
at Microsoft.AspNetCore.Http.DefaultHttpContext.get_RequestServices()
at Microsoft.AspNetCore.Mvc.Controller.get_TempData()
at Microsoft.AspNetCore.Mvc.Controller.View(String viewName, Object model)
at Microsoft.AspNetCore.Mvc.Controller.View(Object model)
我已经在网上寻找了几个小时的人有类似的问题,但我没有找到任何东西。任何帮助是极大的赞赏。提前致谢。
您似乎没有正确使用控制器方法。您需要 return 视图形成端点方法本身。目前,您只是 return 从没有向上传播的 ShowResults 方法中获取信息。试试这个(看看 return 类型):
[HttpPost]
public async Task<IActionResult> getLoc ([FromBody]ZipDto obj)
{
var zip = Int32.Parse(obj.zip);
var location = await _services.GetLatLng(zip);
var climate = await _services.GetTemp(location);
return ShowResults(climate);
}
public IActionResult ShowResults(List<ClimaCellDto> data)
{
try
{
return View(data);
}
catch (Exception ex)
{
throw ex;
}
}
此外,我建议的另一件事是重定向到 GET 方法,而不是直接从 POST 端点 return 访问视图。
我对这一切都是陌生的,并且正处于制作此 Web 应用程序的早期阶段。这仅供我个人使用。我正在尝试在视图中显示网络 api 调用的结果。 api 调用工作正常。我可以看到数据从服务返回并被放置在 DTO 中。它从服务到控制器,但我不确定为什么每次我尝试将数据从控制器发送到视图时,我都会遇到相同的异常:
IFeatureCollection has been disposed. Object name: 'Collection'.
谁能告诉我这是什么意思,我该如何解决这个问题?
这是我的 Startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("mapQUrl", client => { client.BaseAddress = new Uri("https://www.mapquestapi.com/geocoding/v1/address?"); });
services.AddHttpClient("climaUrl", client => { client.BaseAddress = new Uri("https://api.climacell.co/v3/weather/nowcast?"); });
services.AddControllersWithViews();
services.AddScoped<IServices, Services>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
这是我的服务:
public async Task<List<ClimaCellDto>> GetTemp(MapQuestFlatDto loc)
{
List<ClimaCellDto> dataObjects = new List<ClimaCellDto>();
var client = _clientFactory.CreateClient("climaUrl");
string attr = "unit_system=us×tep=5&start_time=now&fields=temp&";
var url = client.BaseAddress + attr + climaUrlParameters;
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url); // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var strContent = await response.Content.ReadAsStringAsync(); //Make sure to add a reference to System.Net.Http.Formatting.dll
dataObjects = JsonConvert.DeserializeObject<List<ClimaCellDto>>(strContent);
return dataObjects;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
return dataObjects;
}
这是从服务接收数据并将其发送到视图的控制器方法:
[HttpPost]
public async void getLoc ([FromBody]ZipDto obj)
{
var zip = Int32.Parse(obj.zip);
var location = await _services.GetLatLng(zip);
var climate = await _services.GetTemp(location);
ShowResults(climate);
}
public IActionResult ShowResults(List<ClimaCellDto> data)
{
try
{
return View(data);
}
catch (Exception ex)
{
throw ex;
}
}
这是视图:
@model IEnumerable<Weather_web_app.DTOs.ClimaCellDto>
@{
ViewData["Title"] = "ShowResults";
}
<h1>ShowResults</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.lat)
</th>
<th>
@Html.DisplayNameFor(model => model.lon)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.observation_time.value)
</td>
<td>
@Html.DisplayFor(modelItem => item.temp.value)
</td>
</tr>
}
</tbody>
</table>
这是调用堆栈:
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ThrowContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.Fetch[TFeature,TState](TFeature& cached, TState state, Func`2 factory)
at Microsoft.AspNetCore.Http.DefaultHttpContext.get_RequestServices()
at Microsoft.AspNetCore.Mvc.Controller.get_TempData()
at Microsoft.AspNetCore.Mvc.Controller.View(String viewName, Object model)
at Microsoft.AspNetCore.Mvc.Controller.View(Object model)
我已经在网上寻找了几个小时的人有类似的问题,但我没有找到任何东西。任何帮助是极大的赞赏。提前致谢。
您似乎没有正确使用控制器方法。您需要 return 视图形成端点方法本身。目前,您只是 return 从没有向上传播的 ShowResults 方法中获取信息。试试这个(看看 return 类型):
[HttpPost]
public async Task<IActionResult> getLoc ([FromBody]ZipDto obj)
{
var zip = Int32.Parse(obj.zip);
var location = await _services.GetLatLng(zip);
var climate = await _services.GetTemp(location);
return ShowResults(climate);
}
public IActionResult ShowResults(List<ClimaCellDto> data)
{
try
{
return View(data);
}
catch (Exception ex)
{
throw ex;
}
}
此外,我建议的另一件事是重定向到 GET 方法,而不是直接从 POST 端点 return 访问视图。