我收到以下错误:当前上下文中不存在名称“Ok”。
如何在我的 Controller API 中解决这个问题? Return Ok 已经嵌入到 Controller 中。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using Newtonsoft.Json;
using WeatherTest.Models;
namespace WeatherChecker.Controllers
{
public class WeatherData
{
[HttpGet("[action]/{city}")]
public async Task<IActionResult> City(string city)
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=YOUR_API_KEY_HERE&units=metric");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawWeather = JsonConvert.DeserializeObject<OpenWeatherResponse>(stringResult);
// Error Here: ** The name 'Ok' does not exist in the current context **
return Ok(new
{
Temp = rawWeather.Main.Temp,
Summary = string.Join(",", rawWeather.Weather.Select(x => x.Main)),
City = rawWeather.Name
});
}
catch (HttpRequestException httpRequestException)
{
// Error Here: The name 'BadRequest' does not exist in the current context
return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
}
}
}
}
}
最佳答案
通过属性路由功能,aspnet 支持 POCO Controller 。它允许使用任何类作为 Controller 。但是你会失去框架基类提供的所有实用程序和助手。
Controller
类继承自 ControllerBase
并添加 View 支持。在您的情况下,ControllerBase
就足够了。
public class WeatherData : ControllerBase // <-
{
// ...
}
关于c# - Net Core 错误名称 'Ok' 在当前上下文中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451416/