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

Car*_*d87 5 c# asp.net-core

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

如何在Controller 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}");
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Kal*_*ten 10

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

该类Controller继承自ControllerBase并添加视图支持。就您而言,ControllerBase就足够了。

public class WeatherData : ControllerBase // <- 
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)