Search code examples
c#asp.net-mvcasp.net-web-apiroutesasp.net-mvc-routing

How to set web api project on mvc project (api route return code 404)?


As first I Built MVC application, with controllers and everthing. After that I realised that I need to make mobile application also, so I put new web api project in solution.

StudentHousingWebProject is MVC and SHApi is web api


I referenced the mvc application, made entity-models, created factory and everything, but when it come down to calling web api controller I get return code 404 not found.

enter image description here

I think that problem is in routing of the project. So here is my WebApiConfig from SHApi project.

    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.EnableCors();
        config.MapHttpAttributeRoutes();
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));


        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: 
            new
            {
                controller="StudentOffer",
                action="Get",
                id = RouteParameter.Optional
            },
            constraints: new {controller = @"(?!web).*"}
        );
    }

And here is my RouteConfig from MVC application.

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

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

And here is my RouteConfig from WebApi project.

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

        routes.MapRoute(
            name: "Default",
            url: "web/{controller}/{action}/{id}",
            defaults: new { action = "Index", id = UrlParameter.Optional }
        );

        routes.MapHttpRoute(name: "DefaultApi",
            routeTemplate:"api/{controller}/{action}/{id}",
            defaults: new { controller = "City",
            action="Get",
            id = RouteParameter.Optional},
            constraints: new { controller = @"(?!web).*" }
            );
    }

I can access MVC controllers easily, but web api Impossible. I tried lot of stuff, but I am sure that I am missing something, so is there anyone with some expirience who can help me, is there any trick to do it like this?

Thank you in Front!


Solution

  • You need to run single instance of both project, firstly web project, because api project have some dependencies from it, and then start api project as single instance, and then you access them with diferent ports.

    You are runing single instance like, right click on project, debug, run as single instance (something like that).