Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API Controller not recognized

I've got a C# project using Web API. I've defined my prefix and routing for my controller, but I keep receiving an error when trying to access the "all" route:

{
"message": "No HTTP resource was found that matches the request URI '.../api/InventoryOnHand/all'.",
"messageDetail": "No type was found that matches the controller named 'InventoryOnHand'."
}

Here's my controller:

[RoutePrefix("api/inventoryonhand")]
public class InventoryOnHandController : ApiController
{
    public InventoryOnHandController(){}
    [HttpGet]
    [Route("all")]
    [CacheOutput(ClientTimeSpan = 50, MustRevalidate = true)]
    public IHttpActionResult GetAllInventoryOnHand()
    {
       // Do stuff
    }
}

My WebApiConfig isn't the issue (I think) because we have other routes working just fine, can't figure out why this one is the odd man out. Our routing in WebApiConfig:

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

EDIT Adding the WebApiConfig file:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // require authenticated users in all controllers/action unless decoratd with "[AllowAnonymous]"
        config.Filters.Add(new AuthorizeAttribute());

        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        config.Services.Add(typeof(IExceptionLogger), new SerilogExceptionLogger());
        ConfigureJsonHandling(config.Formatters.JsonFormatter);

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

        // Web API routes
        config.MapHttpAttributeRoutes();
    }

    private static void ConfigureJsonHandling(JsonMediaTypeFormatter json)
    {
        //make our json camelCase and not include NULL or default values
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        json.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
        json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

    }

EDIT Adding the Startup file (shortened for brevity):

public void Configuration(IAppBuilder app)
    {
        LoggingConfig.ConfigureLogger();

        HttpConfiguration httpConfiguration = new HttpConfiguration();

        var container = IoC.Initialize();
        httpConfiguration.DependencyResolver = new StructureMapResolver(container);

        ConfigAuth(app);

        WebApiConfig.Register(httpConfiguration);


        GlobalConfiguration.Configure(WebApiConfig.Register);


        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(httpConfiguration);

        Log.Logger.ForContext<Startup>().Information("======= Starting Owin Application ======");
    }
like image 887
Thomas Avatar asked Aug 10 '26 05:08

Thomas


1 Answers

Since you are using attributes, you can't get routing by convention. In your WebApiConfig (where you have the route right now), you need to add a line to config.MapHttpAttributeRoutes() like this:

config.MapHttpAttributeRoutes();

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

The call to the MapHttpAttributeRoutes extension method is what will pick up the attributes for the route/routeprefix and create a new route to your method.

like image 179
rmc00 Avatar answered Aug 12 '26 20:08

rmc00



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!