ASP.NET Core WebAPI default route not working

佐手、 提交于 2019-11-28 03:08:54

问题


I've followed several examples suggesting that to set my default route in an ASP.NET Core WebAPI project, I need to replace

app.UseMvc();

with

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action}",
        defaults: new { controller = "Traders", action = "Get" });
});

But when I run it defaults to localhost:54321/api/values and it should default to localhost:54321/Traders

What's wrong?


回答1:


As @tmg mentioned, do the following:

Right click your web project -> Select Properties -> Select the Debug tab on the left -> Then edit the 'Launch Url' field to set your own default launch url.




回答2:


You can change the default route by modifying LaunchSettings.json file as shown




回答3:


Follow the steps below.

Create a base controller for your API that extends base controller of dotnet core:

using Microsoft.AspNetCore.Mvc;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    public abstract class ControllerApiBase : Controller
    {

    }
}

And inherit the base class in your API controllers:

using Microsoft.AspNetCore.Mvc;
using WebApi.Dtos;

namespace WebApi.Controllers
{
    public class PingController : ControllerApiBase
    {
        public PingDto Get()
        {
            return new PingDto
            {
                Version = "0.0.0"
            };
        }
    }
}


来源:https://stackoverflow.com/questions/44723893/asp-net-core-webapi-default-route-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!