我正在尝试学习asp.net核心,因此根据official site,我安装了它的sdk并通过以下命令创建简单的Web api:
dotnet new webapi -o TodoApi
我的想法是vscode。 这是我的控制器类:
namespace TodoApi.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";
}
[HttpGet("api/cities")]
public JsonResult GetCities(){
return new JsonResult(new List<object>(){
new {id=1, name = "new york city"},
new {id = 2 , name = "gorgan"}
});
}
}
}
在此示例中,我添加了GetCities
方法。在邮递员中,当我使用
https://localhost:5001/api/values
我得到结果:
[
"value1",
"value2"
]
但是当我调用已添加到控制器中的方法时,在postamn中
https://localhost:5001/api/cities
我有404 Not Found
,我必须使用此网址https://localhost:5001/api/values/api/cities
才能得到正确的答案?
有什么问题?我该如何解决?
这是设置:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:34842",
"sslPort": 44370
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": false,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"TodoApi": {
"commandName": "Project",
"launchBrowser": false,
"launchUrl": "api/values",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
和dotnet信息:
groot@groot-Product:~$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 2.1.700
Commit: c2ef055a0f
Runtime Environment:
OS Name: ubuntu
OS Version: 18.04
OS Platform: Linux
RID: ubuntu.18.04-x64
Base Path: /usr/share/dotnet/sdk/2.1.700/
Host (useful for support):
Version: 2.1.11
Commit: d6a5616240
.NET Core SDKs installed:
2.1.700 [/usr/share/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.11 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.11 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.11 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
groot@groot-Product:~$
答案 0 :(得分:1)
您的控制器名称为ValuesController。 ASP.Net使用控制器名称作为路径。因此,在这种情况下,您应该致电
api/values/GetCities
并删除
[HttpGet("api/cities")]
方法的属性。
如果您希望路径为
GET api/cities
创建一个新的控制器,并将您的代码复制到该控制器中,将您的方法重命名为Get()
,然后坐下来让代码为您完成路由。