【发布时间】:2020-06-29 00:54:50
【问题描述】:
您好,我正在按照教程中的说明进行操作。使用dotnet new webapi,我得到了一个与课程所示不同的项目,并且来自我测试过的另一个人的计算机。我们得到的文件基本相同,但我有一个额外的WeatherForcast.cs,而不是ValuesController.cs,我得到的是WeatherForcastController.cs,其中包含完全不同的代码,我将在底部发布。
Program.cs 和Startup.cs 也有一些较小的差异
造成这种差异的原因是什么?如何从示例中按照我尝试的方式生成文件?
回答:答案是它默认为我安装的 .NET SDK 3.1,但本教程使用 .NET SDK 2.2。运行命令 dotnet new webapi --framework netcoreapp2.2 会得到我正在寻找的这个 webapi 的版本。
我的控制器WeatherForcastController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Testing.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
示例及其他电脑控制器ValuesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace CretaceousPark.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
【问题讨论】:
-
检查您使用的 .net 核心版本。版本可能与教程中的版本和您安装的版本不同。
标签: c# asp.net asp.net-core asp.net-web-api asp.net-core-webapi