如何将Web API控制器添加到现有的ASP.NET Core MVC?

Ale*_* G. 16 c# asp.net-core-mvc asp.net-core asp.net-core-webapi asp.net-core-routing

我使用默认的ASP.NET Core MVC模板创建了一个项目.我想在下面创建一个RESTful API /api/{Controller}.我添加了一个新的Web API控制器(标准Web API控制器类模板),但我无法调用它.我收到一条错误消息,指出无法找到该页面.我尝试在Startup.cs中添加一个路由,但它没有做任何事情:

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});
Run Code Online (Sandbox Code Playgroud)

编辑:

就像我说的,这都是默认模板.这是我添加的Web API控制器:

[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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 11

我很幸运用 v3.1 做到了这一点:

将文件夹控制器添加到项目中。将名为 TestController 的Controller添加到该文件夹​​。然后将以下内容添加到 Startup.cs:

services.AddControllers();
Run Code Online (Sandbox Code Playgroud)

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddControllers();
    }
Run Code Online (Sandbox Code Playgroud)

和:

endpoints.MapControllers();
Run Code Online (Sandbox Code Playgroud)

app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
        });
Run Code Online (Sandbox Code Playgroud)

然后我就可以调用/api/Test。


Nko*_*osi 8

两件事情.

首先,当使用基于约定的路由时,更多特定路由应该出现在更通用的路由之前以避免路由冲突.

app.UseMvc(routes =>
{
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

其次,您已经在控制器上使用属性路由,所以本应该能够路由到控制器,除了您在控制器上没有可接受的路由模板这一事实 /api/{Controller}

这将需要一个默认路由

[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
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*oun 6

如果有人在将webapi添加到.net core MVC时仍然有问题,只需在类之前插入[ApiController][Route("api/[controller]")]属性即可解决问题:

[Route("api/[controller]")]
[ApiController]
public class ListController
{ ... }
Run Code Online (Sandbox Code Playgroud)

我没有添加路由映射Startup.cs,但仍然运行良好。我使用的 .net 版本是 2.1.402


Ale*_* G. 3

更新到最新版本的 ASP.NET Core v2.0.1(需要 VS2017 的版本)后,问题自行解决。我认为这可能是旧版本的错误或缺点。