如何将api添加到服务器?

时间:2019-12-29 12:13:51

标签: c# asp.net-core asp.net-core-mvc asp.net-core-routing

我在项目中添加了一个api控制器,并更改了启动文件。但仍然无法正常工作

[Route("api/[controller]")]
[ApiController]
public class HomeApiController : ControllerBase
{
    // GET: api/HomeApi
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

}

routes.MapRoute(
    name: "default",
    template: "{culture=en}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
    name: "api",
    template: "api/{culture=en}/{controller=Home}/{action=Index}/{id?}");

1 个答案:

答案 0 :(得分:3)

控制器上的route属性

[Route("api/[controller]")]
public class HomeApiController : ControllerBase

将映射到

api/homeapi

因为控制器的名称被路由模板中的[controller]令牌代替。

相应地重命名控制器

[Route("api/[controller]")]
[ApiController]
public class HomeController : ControllerBase

或更新路线模板

[Route("api/home")]
[ApiController]
public class HomeApiController : ControllerBase

引用Routing to controller actions in ASP.NET Core

引用Routing in ASP.NET Core