[英]Routing migration from ASP.NET WebAPI to ASP.NET Core WebAPI, ambiguous method issue
[英]ASP.NET Core WebAPI Routing
我創建使用ASP.NET核心的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/zh-cn/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":"A@BB.COM","Password":"1"}
Output in response header:
HTTP/1.1 404 Not Found
[Route("api/[controller]")]
上的[Route("api/[controller]")]
,以及操作上的[HttpPost]
意味着該操作將在/api/[controller]
可用。 因此,在您的情況下/api/User
。
除非您在路由模板中包括[action]
,否則[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請求。
您尚未完全定義路線。
[Route("api/[controller]")]
創建URL的/api/User
部分,但您尚未在操作中指定其余路由。
因此,您的請求應從更改為http://localhost:8011/api/User/RegisterUser
更改為http://localhost:8011/api/User
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.