Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Web API Route Prefix

I have a web api that runs in a WPF C# application. I have used Owin to implement it. If I send request by using /api prefix then it works as I expected.

http://localhost:8080/api/test/config?no=7

However, I need to remove the /api prefix. If I try the request below it does not work when I tried example code below.

http://localhost:8080/test/config?no=7

Is it possible to remove api word from requests?

Here is my code:

WebApp.Start<Startup>(url: "http://*:8080/");

    class Startup
    {
        Type ValuesControllerType = typeof(TestController);

        public void Configuration(IAppBuilder Builder)
        {
            var Instance = new HttpConfiguration();

            Instance.MapHttpAttributeRoutes();

            Instance.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "{controller}/{action}/{request}",
               defaults: new { request = RouteParameter.Optional }
           );

            Builder.UseWebApi(Instance);
        }
    }

    [RoutePrefix("test")]
    public class TestController : ApiController
    {    
        [HttpGet]
        [Route("config")]
        public string Config(string No)
        {
            try
            {
                return No;
            }
            catch (Exception e)
            {
                return string.Empty;
            }
        }
    }

I tried the answer in C# web api route for a webservice but did not work.

I get following error:

HTTP Error 503. The service is unavailable.
like image 908
Demir Avatar asked Jan 30 '26 21:01

Demir


2 Answers

On the Rest api open your WebApiConfig.cs you should find the following code:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}"
        );

Try removing api from there

like image 118
Arno Avatar answered Feb 02 '26 23:02

Arno


I faced the same problem in .Net Core 2 WebAPI project

here is my solution

[Produces("application/json")]
[Route("[controller]")]
public class DefaultController : Controller
{
    [Route("getUser")]

    public IActionResult GetUsers()
    {
         return Ok();
    }
}

the address is http://localhost:port/default/getuser

like image 41
Mahdi Avatar answered Feb 03 '26 01:02

Mahdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!