我刚刚启动了 VS,并从模板创建了一个新的 .net core Web Api 项目,它的工作方式与您期望的一样:
[ApiController]
[Route("api/TheApi")]
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();
}
[HttpGet("OtherGet")]
public IEnumerable<WeatherForecast> OtherGet()
{
var rng = new Random();
return Enumerable.Range(1, 2).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
有效网址:
Startup.cs 如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
更新:另外请记住,您不能在一个控制器中拥有多个 GET/POST 等方法,只有当您像我一样为其他(或所有)使用注释时使用 OtherGet:HttpGet("OtherGet")]。如果你不使用这个注解并且有多个 GET、POST 等方法,你会遇到异常:AmbiguousMatchException: The request matched multiple endpoints.