Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom WebApi routing not working

I am trying to create a custom route for a web api controller:

[System.Web.Http.RoutePrefix("api/admin")]
public class AdminApiController : BaseApiController
{
    [Route("~/echo")]
    public string Echo()
    {
        return "Hello World";
    }
}

I expect to go to http://example.com/api/admin/echo and receive 'Hello world' but in stead I get an error:

<Error>
    <Message>
        No HTTP resource was found that matches the request URI 'http://example.com/api/admin/echo'.
    </Message>
    <MessageDetail>
    No type was found that matches the controller named 'admin'.
    </MessageDetail>
</Error>
like image 899
Andrey Avatar asked Jul 14 '26 21:07

Andrey


1 Answers

Replace the tilde (~)

A tilde (~) on the method attribute overrides the route prefix of the controller:

[RoutePrefix("api/admin")]
public class AdminApiController : BaseApiController {
    // GET /api/admin/echo
    [HttpGet]
    [Route("echo")] 
    public string Echo() {
        return "Hello World";
    }
    // GET /echo
    [HttpGet]
    [Route("~/echo")]
    public string Echo2() {
        return "Hello World 2";
    }
}

Just to be safe you also need to make sure that you Enable Attribute Routing

To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is defined in the System.Web.Http.HttpConfigurationExtensions class.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
like image 67
Nkosi Avatar answered Jul 17 '26 18:07

Nkosi



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!