IFeatureCollection已被处置。对象名称:"集合"。从控制器转到视图



我对这一切都是新手,而且还处于制作这个web应用程序的早期阶段。这只是我个人用的。我正在尝试在视图中显示web api调用的结果。api调用运行良好。我可以看到数据从服务中返回,并被放入DTO罚款中。它从服务到控制器,但我不确定为什么每次我试图将数据从控制器发送到视图时,我都会得到同样的异常:

IFeatureCollection已被释放。对象名称:"集合"。

有人能告诉我这意味着什么吗?我该如何解决这个问题?

这是我的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&timestep=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)

我在网上找了几个小时有类似问题的人,但什么也没找到。非常感谢您的帮助。提前谢谢。

您似乎没有正确使用控制器方法。您需要从端点方法本身返回视图。目前,您只是从ShowResults方法返回,该方法没有向上传播。试试这个(看看返回类型(:

[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端点返回视图。

最新更新