c# - Net Core 错误名称 'Ok' 在当前上下文中不存在

标签 c# asp.net-core

我收到以下错误:当前上下文中不存在名称“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/

相关文章:

c# - 使用 NUnit 测试 Windows 窗体逻辑

c# - 项目中的依赖Twilio不支持框架DNXCore,版本=v5.0

asp.net-mvc - 为什么 bool 复选框的 ASP.NET Core 标记帮助程序不显示标签?

c# - 如何修复对象引用未设置到对象实例的 MySql 连接问题

c# - 如何正确退出 C# 应用程序?

c# - 公共(public)与私有(private){get, set}

c# - net.core/asp.net identity/openid connect 关联失败

c# - StreamReader 读取包含的最后一行

c# - 是否可以在多个中间件中使用同一个路由器?

c# - .NET核心3.0 : Razor views don't automatically recompile on change