6

When I run a .NET Core Web API project, I get a URL that looks like this: http://localhost:5000/api/...

How can I change the /api/ part of the URL to something else? i.e. - http://localhost:5000/myservice/...

I am using Kestrel as my web host.

TylerH
  • 20,799
  • 66
  • 75
  • 101
David Derman
  • 821
  • 2
  • 9
  • 19

2 Answers2

10

It depends on how you have the project setup. By default I believe it uses attribute routing. In your controller you should see something like this

[Route("api/[controller]")]
public class ValuesController : Controller
{

Where the [Route("api/[controller]")] would just need to be changed to [Route("myservice/[controller]")]

If you wanted to do it Globally you could do it like this.

app.UseMvc(routes =>
{
   routes.MapRoute("default",  "myservice/{controller=values}/{action=get}/{id?}");
});

Although I myself don't use this, and it's not exactly what MS Recommends for a Web Api. You can read more here.

Mixed Routing MVC applications can mix the use of conventional routing and attribute routing. It's typical to use conventional routes for controllers serving HTML pages for browsers, and attribute routing for controllers serving REST APIs.

Woot
  • 1,759
  • 1
  • 16
  • 23
  • Ah, thanks! I will mark this as the answer. On a related note, is there a way to do that globally rather than in every controller? – David Derman Feb 23 '17 at 20:06
  • Yeah I favor attribute routing myself because I have control over the url, but you can do it. Let me edit the answer so the code is more clear. – Woot Feb 23 '17 at 20:08
4

You could just install microsoft.aspnetcore.http.abstractions nuget package and use UsePathBaseExtensionsextension method on IApplicationBuilder in your Startup.Configure method like so:

app.UsePathBase("/api/v1");
O.MeeKoh
  • 1,976
  • 3
  • 24
  • 53