Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Net核心错误当前上下文中不存在名称“Ok”_C#_Asp.net Core - Fatal编程技术网

C# Net核心错误当前上下文中不存在名称“Ok”

C# Net核心错误当前上下文中不存在名称“Ok”,c#,asp.net-core,C#,Asp.net Core,我收到以下错误:当前上下文中不存在名称“Ok” 如何在控制器API中解决此问题?返回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.Model

我收到以下错误:当前上下文中不存在名称“Ok”

如何在控制器API中解决此问题?返回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}");
                }
            }
        }
    }
}

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

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

public class WeatherData : ControllerBase // <- 
{
    // ...
}
您必须从Controller或ControllerBase继承