SelfHosted AspNet WebAPI与控制器类在不同的项目中

10 self-hosting multiple-projects asp.net-web-api

我使用Visual Studio 2012(.NET Framework 4.5)创建了一个SelfHosted AspNet WebAPI.我为WebAPI启用了SSL.在同一项目中定义控制器时,它工作正常.

但是当我添加另一个包含控制器的项目的引用时,它给出了以下错误:

No HTTP resource was found that matches the request URI 'https://xxx.xxx.xxx.xxx:xxxx/hellowebapi/tests/'.

我已经为HttpSelfHostConfiguration和MessageHandler创建了自定义类.

解决这个问题的任何帮助对我来说都是一个很好的时间.

提前感谢.

Kir*_*lla 8

您可以编写一个简单的自定义程序集解析程序,以确保加载引用的程序集以使控制器探测工作.

以下是菲利普关于此的一篇不错的帖子:http:
//www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/

样品:

class Program
{
    static HttpSelfHostServer CreateHost(string address)
    {
        // Create normal config
        HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address);

        // Set our own assembly resolver where we add the assemblies we need
        CustomAssembliesResolver assemblyResolver = new CustomAssembliesResolver();
        config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);

        // Add a route
        config.Routes.MapHttpRoute(
          name: "default",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { controller = "Home", id = RouteParameter.Optional });

        HttpSelfHostServer server = new HttpSelfHostServer(config);
        server.OpenAsync().Wait();

        Console.WriteLine("Listening on " + address);
        return server;
    }

    static void Main(string[] args)
    {
        // Create and open our host
        HttpSelfHostServer server = CreateHost("http://localhost:8080");

        Console.WriteLine("Hit ENTER to exit...");
        Console.ReadLine();
    }
}

public class CustomAssembliesResolver : DefaultAssembliesResolver
{
    public override ICollection<Assembly> GetAssemblies()
    {
        ICollection<Assembly> baseAssemblies = base.GetAssemblies();

        List<Assembly> assemblies = new List<Assembly>(baseAssemblies);

        var controllersAssembly = Assembly.LoadFrom(@"C:\libs\controllers\ControllersLibrary.dll");

        baseAssemblies.Add(controllersAssembly);

        return assemblies;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @DarrelMiller:这取决于你是否在另一个程序集中引用一个导致程序集加载的类型,在这种情况下探测就可以了.在上面的示例中,例如,在不使用程序集解析器的情况下,我可以执行类似`Type valuesControllerType = typeof(ControllersLibrary.ValuesController);`这样的操作,这会导致程序集被加载. (5认同)