我最近开始学习C#和ASP。我刚刚使用以下命令创建了一个ASP项目:
dotnet new webapi -n ProjectName
它有默认的示例项目。我可以构建并运行它,并使用以下URL从浏览器调用它:
http://localhost:5068/WeatherForecast
我不明白URL的***WeatherForecast***部分是如何确定的,因为我在任何地方都找不到该特定字符串。
这是控制器的内容:
using Microsoft.AspNetCore.Mvc;
namespace ProjectName.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(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
1条答案
按热度按时间dgsult0t1#
就在那儿
Route属性中有
[controller]
,这意味着:使用这个类的类型名而不使用单词Controller
作为路由。因此,如果你想要一个不同的url,要么将
WeatherForecastController
重命名为MyApiController
,要么在route属性中显式显示:[Route("myapi")]
另请参见路由模板[controller]、[action]、[area]中的令牌替换