[英]How to add Web API controller to an existing ASP.NET Core MVC?
I created a project using the default ASP.NET Core MVC template.我使用默认的 ASP.NET Core MVC 模板创建了一个项目。 I would like to also create a RESTful API under /api/{Controller}
.我还想在/api/{Controller}
下创建一个 RESTful API 。 I added a new Web API controller (standard Web API controller class template) but I can't call it. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found.我收到一条错误消息,提示找不到该页面。 I tried adding a route in Startup.cs but it doesn't do anything:我尝试在Startup.cs中添加一条路线,但它什么也没做:
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});
EDIT:编辑:
Like I said, it's all default templates.就像我说的,这都是默认模板。 Here's the Web API Controller that I added:这是我添加的 Web API Controller:
[Route("api/[controller]")]
public class AdminController : Controller
{
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
Two things.两件事。
First, when using convention-based routing, more specific routes should come before more generic routes to avoid route conflicts.首先,当使用基于约定的路由时,更具体的路由应该放在更通用的路由之前,以避免路由冲突。
app.UseMvc(routes =>
{
routes.MapRoute(name: "api", template: "api/{controller=Admin}");
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
Secondly, you are already using attribute routing on the controller so should have been able to route to the controller except for the fact that you do not have a routing template on the controller that would accept /api/{Controller}
其次,您已经在控制器上使用属性路由,因此应该能够路由到控制器,除非您在控制器上没有接受/api/{Controller}
的路由模板
That would require a default route.那将需要一个默认路由。
[Route("api/[controller]")]
public class AdminController : Controller {
[HttpGet("")] //Matches GET api/admin <-- Would also work with [HttpGet]
public IActionResult Get() {
return Ok();
}
[HttpGet("{id}")] //Matches GET api/admin/5
public IActionResult Get(int id) {
return Ok("value");
}
//...other code removed for brevity
}
If someone still have problem in adding webapi to .net core MVC, just inserting [ApiController]
and [Route("api/[controller]")]
attributes before class solves the problem:如果有人在将 webapi 添加到 .net core MVC 时仍然有问题,只需在 class 之前插入[ApiController]
和[Route("api/[controller]")]
属性即可解决问题:
[Route("api/[controller]")]
[ApiController]
public class ListController
{ ... }
I didn't added a route mapping in Startup.cs
and still working well.我没有在Startup.cs
添加路由映射,但仍然运行良好。 The version of .net that I am using is 2.1.402我使用的 .net 版本是 2.1.402
After updating to the latest version of ASP.NET Core, v2.0.1 (the one that needs VS2017), the problem resolved itself.更新到最新版本的ASP.NET Core v2.0.1(需要VS2017的那个)后,问题自行解决。 I think it was probably a bug or shortcoming in the old version.我认为这可能是旧版本中的错误或缺点。
I had luck doing this with v3.1:我很幸运用 v3.1 做到了这一点:
Add Folder Controllers to the project.将文件夹控制器添加到项目中。 Add Controller , named TestController, to the folder.将名为 TestController 的Controller添加到文件夹中。 Then add the following to the Startup.cs:然后将以下内容添加到 Startup.cs:
services.AddControllers();
to到
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddControllers();
}
and:和:
endpoints.MapControllers();
to到
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
Then I was able to call /api/Test.然后我就可以调用/api/Test。
Try setting name to "Admin"尝试将名称设置为“管理员”
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Admin",
template: "api/{controller=Admin}");
});
Running existing .net core MVC:运行现有的 .net 核心 MVC:
In order to add api controllers to existing .net core 6 mvc application, Open Program.cs file, add following codes:为了将 api 控制器添加到现有的 .net 核心 6 mvc 应用程序,打开 Program.cs 文件,添加以下代码:
//for apis
builder.Services.AddRazorPages();
builder.Services.AddControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
Now go ahead and add a new controller:现在前面是 go 并添加一个新的 controller:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
//endpoint: http://localhost:5207/api/test/strings
[HttpGet("strings")]
public IActionResult TestMethod()
{
return Ok(new string[]{
"23", "24"});
}
}
Testing Endpoint here This works for me in .net core 6在此处测试端点这在 .net 核心 6 中对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.