Configure route to api to subfolder

i'm developing a webapi using MVC 4. I have a doubt about routers. How to route to a subfolder under my site. For example:

www.site.com/Service

My WebApi app is on service folder. My Main Page works fine, but the API is not found.

Here is my route by default:

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

I want to call

www.site.com/Service/api/{controller}/{id}

Is there a way to do this?

[Edit] I added Service area into Ares folder, because already exists a area to HelpPage in the template for WebApi MVC 4. Inside this folder i added the controlers.

Here is the Service area class

public class ServiceAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Service";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Service_default",
            "Service/api/{controller}/{id}",
            new { id = UrlParameter.Optional }
        );
    }
}

I dont know if this help, my site www.site.com is just a web site, i added and converted this folder Service into application on my iis. [/Edit]

Upvotes: 3

Views: 2910

Answers (1)

Lin
Lin

Reputation: 15188

You need to create your own AreaRegistration like below to make it work.

 public class ServiceAreaRegistration : AreaRegistration
    {
        public override string AreaName 
        {
            get{ return "Service";}
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.Routes.MapHttpRoute(
                name: "ServiceDefaultApi",
                routeTemplate: "Service/api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

You also need to make sure you have below code in Application_Start()

AreaRegistration.RegisterAllAreas();

Update: Your folder structure should looks like:

enter image description here

Upvotes: 4

Related Questions