How to configure Web Api 2 to look for Controllers in a separate project? (just like I used to do in Web Api)

前端 未结 8 1813
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 17:40

I used to place my controllers into a separate Class Library project in Mvc Web Api. I used to add the following line in my web api project\'s global.asax to look for contro

8条回答
  •  醉话见心
    2020-12-04 18:25

    It should work as is. Checklist

    • Inherit ApiController
    • End controller name with Controller. E.g. ValuesController
    • Make sure WebApi project and class library project reference same WebApi assemblies
    • Try to force routes using attribute routing
    • Clean the solution, manually remove bin folders and rebuild
    • Delete Temporary ASP.NET Files folders. WebApi and MVC cache controller lookup result
    • Call `config.MapHttpAttributeRoutes(); to ensure framework takes attribute routes into consideration
    • Make sure that the method you are calling is made to handle correct HTTP Verb (if it is a GET web method, you can call via browser URL, if it is POST you have to otherwise craft a web request)

    This controller:

    [RoutePrefix("MyValues")]
    public class AbcController : ApiController
    {
        [HttpGet]
        [Route("Get")]
        public string Get()
        {
            return "Ok!";
        }
    }
    

    matches this url:

    http://localhost/MyValues/Get (note there is no /api/ in route because it wasn't specified in RoutePrefix.


    Controller lookup caching: This is default controller resolver. You will see in the source code that it caches lookup result.

    /// 
    /// Returns a list of controllers available for the application.
    /// 
    /// An  of controllers.
    public override ICollection GetControllerTypes(IAssembliesResolver assembliesResolver)
    {
        HttpControllerTypeCacheSerializer serializer = new HttpControllerTypeCacheSerializer();
    
        // First, try reading from the cache on disk
        List matchingTypes = ReadTypesFromCache(TypeCacheName, IsControllerTypePredicate, serializer);
        if (matchingTypes != null)
        {
            return matchingTypes;
        }
    ...
    }
    

提交回复
热议问题