8

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.

1
  • This should be quite a simple change in the routing config in Startup.cs. Commented Feb 23, 2017 at 20:01

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.