我正在使用ASP.NET Core创建API,下面是我的控制器代码。
我在下面给出了控制器和启动代码,以及提琴手的请求/响应日志。我收到404找不到错误。请告诉我我想念什么?
[Route("api/[controller]")]
public class UserController : Controller
{
[HttpPost]
public string RegisterUser(User newUser)
{
// Code to register user in system
return succecss/failure message
}
}
我尝试从中建议的属性路由
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing但仍然没有运气。我不确定我缺少什么。
请注意,使用Web API模板,Startup.cs中没有默认路由:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
以下是我的提琴手要求:
URL: http://localhost:8011/api/User/RegisterUser
Verb= post
User-Agent: Fiddler
Host: localhost:8011
Content-Type: application/json
Content-Length: 77
Request body
{"FirstName": "TEST FirstName", "LastName": "Test Last Name", "EmailId":"[email protected]","Password":"1"}
Output in response header:
HTTP/1.1 404 Not Found
最佳答案
控制器上的[Route("api/[controller]")]
以及操作上的[HttpPost]
意味着该操作将在/api/[controller]
上可用。因此,根据您的情况/api/User
。
除非您在路由模板中包括[action]
,否则操作的方法名称将不包括在路由中。
因此,尝试对/api/User
进行POST,或将控制器上的route属性更改为[Route("api/[controller]/[action]")]
。
请注意,API项目模板的Startup
中不包含默认路由的原因是,您需要使用API显式配置它们。这样,路由就是您的应用程序设计的一部分。使用RESTful API,通常以表示“资源”的方式设计API。然后,您使用HTTP动词来指示您的实际操作。包含的ValuesController
实际上是一个很好的例子:
// GET api/values
[HttpGet] Get()
// => Get all values
// GET api/values/5
[HttpGet("{id}")] Get(int id)
// => Get a single value
// POST api/values
[HttpPost] Post([FromBody] string value)
// => Add a new value
// PUT api/values/5
[HttpPut("{id}")] Put(int id, [FromBody] string value)
// => Set/replace a value
// DELETE api/values/5
[HttpDelete("{id}")] Delete(int id)
// => Delete a value
默认情况下,那里没有任何路由,因此您不会意外地在路由中得到方法名称(因为方法名称通常是命令性的单词组合,因此使它更RPC而不是REST)。相反,您将不得不故意将您的方法公开为带有动词的实际路由。
例如,您的
UserController
可能是针对“用户”资源的。因此,注册用户可能是对/api/User
的POST请求。关于c# - ASP.NET Core WebAPI路由,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49374448/