Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default controller action for Web API in Asp.Net MVC

My Web API on an Asp.Net MVC web app is returning 404 error when receiving requests that don't specify any controller. The calls that are returning 404 error are:

https://myWebApp/api/

The goal would be to handle these type of requests without returning error and return something like "true" or "new EmptyResult()".

Current routing for the Web API includes the following in WebApiConfig.cs

public static class WebApiConfig
    {                
        public static void Register(HttpConfiguration config)
        {   
            config.Filters.Add(new IdentityBasicAuthenticationAttribute());

            config.MapHttpAttributeRoutes();

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

While I have routes explicitly defined for each API controller:

[IdentityBasicAuthentication]
[Authorize]
public class myApi1Controller : ApiController
{
    [HttpGet]
    [Route("api/myApi1")]
    public string Get(string id) { ... }
}

I have tried to route these calls to a default API or MVC controller without success.

My current RouteConfig for the MVC app is:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "myWebApp.Controllers" }
        );
    }
}

The order in which these are called is:

protected void Application_Start()
{                    
    AreaRegistration.RegisterAllAreas();                
    GlobalConfiguration.Configure(WebApiConfig.Register); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}
like image 904
donquijote Avatar asked Oct 17 '22 08:10

donquijote


1 Answers

Create a controller to handle that route so it does not fail with not found

Like

[RoutePrefix("api")]
public class MyEmptyController : ApiController {
    //GET api
    [HttpGet]
    [Route("")]
    public IHttpActionResult Get() { 
        return StatusCode(HttpStatusCode.NoContent); //204
    }
}

Using attribute routing as it is already enabled via config.MapHttpAttributeRoutes(); in WebApiConfig

like image 154
Nkosi Avatar answered Oct 21 '22 01:10

Nkosi