Matthew Layton
Matthew Layton

Reputation: 42229

ASP.NET Core WebAPI default route not working

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?

Upvotes: 18

Views: 27698

Answers (3)

Bruno Pereira
Bruno Pereira

Reputation: 721

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"
            };
        }
    }
}

Upvotes: 2

YG Abhi
YG Abhi

Reputation: 261

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

enter image description here

Upvotes: 11

ctv
ctv

Reputation: 1061

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.

Properties Pane of the project

Upvotes: 57

Related Questions