Net Core 错误:当前上下文中不存在名称为 'Ok' 的内容。

25

我收到以下错误:The name 'Ok' does not exist in the current context。

如何在我的控制器API中解决这个问题?Return Ok已经嵌入到控制器中了。

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}");
                }
            }
        }
    }
}

3
你必须继承自 Controller 或者 ControllerBase - Kalten
1个回答

51

通过属性路由特性,aspnet支持POCO控制器。这允许使用任何类作为控制器,但您将失去框架基类提供的所有实用程序和帮助程序。

Controller类继承自ControllerBase并添加视图支持。在您的情况下,ControllerBase就足够了。

public class WeatherData : ControllerBase // <- 
{
    // ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接