Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the "/api" part of the url in ASP.Net Core

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.

like image 820
David Derman Avatar asked Dec 15 '22 00:12

David Derman


2 Answers

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.

like image 72
Woot Avatar answered Jan 18 '23 23:01

Woot


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");
like image 43
O.MeeKoh Avatar answered Jan 18 '23 22:01

O.MeeKoh