ASP.Net WebAPI area support

后端 未结 5 2335
庸人自扰
庸人自扰 2020-12-02 22:49

I am trying to add some WebAPI support to my asp.net 4 RC site, and wish to put it into an area. I have seen that someone managed to get this running on the beta (here) ,

5条回答
  •  旧时难觅i
    2020-12-02 23:20

    ASP.NET MVC 4 doesn't support WebAPI in Areas.

    It is possible to extend DefaultHttpControllerSelector to do this, but you should carefully read this excellent (and short) article: ASP.NET MVC 4 RC: Getting WebApi and Areas to play nicely. It works great.

    I've successfully tested this solution with portable areas (MVCContrib). Basically, you have to:

    • Put extension methods "AreaRegistrationContextExtensions" in the PA project (required from PortableAreaRegistration.RegisterArea() method): you can copy the static class into the PA project but I suggest to put it into a shared project.
    • Add the class "AreaHttpControllerSelector" (inherited from DefaultHttpControllerSelector) into the host project.
    • Add to Global.asax App_Start() the following line:

      GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new AreaHttpControllerSelector(GlobalConfiguration.Configuration));

    There is one caveat with the implementation of AreaHttpControllerSelector: the area name must correspond to the ApiController's namespace. For example, this is my PortableAreaRegistration class:

    namespace PortableAreasSample.MembershipArea
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using MvcContrib.PortableAreas;
        using System.Web.Http;
        using System.Web.Mvc;
        using System.Web.Routing;
    
        public class MembershipRegistration : PortableAreaRegistration
        {
            public override void RegisterArea(System.Web.Mvc.AreaRegistrationContext context, IApplicationBus bus)
            {
                // GET /MembershipArea/GetAllUsers
                context.MapHttpRoute("MembershipApi",
                    AreaName + "/{controller}/{id}",
                    new { area=AreaName, controller = "GetAllUsers", id = RouteParameter.Optional });
            }
    
            public override string AreaName
            {
                get { return "MembershipArea"; }
            }
        }
    }
    

提交回复
热议问题