ASP.NET RESTful API URL设置及WeatherForecast路由来源疑问
ASP.NET WebAPI 接口URL的设置逻辑
你找不到的WeatherForecast其实是通过控制器的路由特性自动生成的,核心就在这段代码里:
[ApiController] [Route("[controller]")] // 关键所在 public class WeatherForecastController : ControllerBase
[Route("[controller]")]是控制器级别的路由模板,其中[controller]是ASP.NET内置的路由占位符,运行时会自动把控制器类名的Controller后缀去掉,替换成这个占位符的值。- 你的控制器类名叫
WeatherForecastController,去掉Controller后缀后就是WeatherForecast,这就是你访问的URL里/WeatherForecast的来源。 - 再配合方法上的
[HttpGet]特性(标记该方法响应GET请求),在没有额外指定路径的情况下,完整的访问路径就是http://localhost:5068/WeatherForecast。
如果想自定义URL路径,直接修改[Route]里的内容即可:
- 比如改成
[Route("my-weather")],访问路径就变成http://localhost:5068/my-weather; - 或者设置多级路径
[Route("api/[controller]")],路径就变成http://localhost:5068/api/WeatherForecast。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

