4
votes

I have a few controllers of my own and the routing is basically made from attributes. The problem is, when i mock my http requests with Postman, it seems that the program does not know about the routing that was provided.

My controller looks like this :

[RoutePrefix("register")]
public class RegisterController : ApiController
{
    private readonly IRegisterService _service;

    public RegisterController(IRegisterService service)
    {
        _service = service;
    }

    [HttpPost]
    [Route("simple")]
    public void RegisterSimple(RegisterArgs args)
    {
        _service.RegisterSimple(args);
    }
}

Note that Global.asax.cs has a call to configuration that is compatible with Web Api 2 :

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);

        // DI Registrations
    }
}

... and WebApiConfig calls MapHttpAttributeRoutes() :

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

When I try calling POST method from Postman with uri

http://localhost:63575/api/register/simple

I get the following answer :

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:63575/api/register/simple'.",
    "MessageDetail": "No action was found on the controller 'Register' that matches the request."
}

I do believe that the problem is within the routing configuration. I debugged it, and after both method calls (config.MapHttpAttributeRoutes() and config.Routes.MapHttpRoute) the config has only two Routes : one with empty RouteTemplate ("") and other with provided from MappHttpRoute() call ("api/{controller}/{id}"). My question is - how do I configure the routing via attributes properly?

1

1 Answers

1
votes

Your controller-level route prefix should start with "api" like following:

[RoutePrefix("api/register")]
public class RegisterController : ApiController