ASP.Net Core Web API convention-based routing?

左心房为你撑大大i 提交于 2019-12-01 03:25:31

This is not works, as mapping to action method is not defined. AFAIK, you may achieve the WebApi REST like routing ONLY using the attribute routing and you may define it on controller level:

[Route("api/[controller]")]
public class TestController : Controller
{
    [HttpGet]
    public long Get() => DateTimeOffset.Now.ToUnixTimeSeconds();
}

Update: have found this github issue Web API not working with convention based routin and:

for ASP.NET Core MVC we decided to adopt MVC 5.x's conventional routing approach and not Web API 2.x's approach. With the conventional routing approach, the route must specify both a controller and an action.


You may change route template to

template: "api/{controller}/{action}/{id?}"

But in this case, your URL will be /api/test/get.


Update 2 (based on the guide): you can include the NuGet package for Microsoft.AspNetCore.Mvc.WebApiCompatShim and still use ApiController. The code is on GitHub if you are curious as to what it does. Then you can define the WebApi routing:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseMvc(routes =>
    {
        routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!