SelfHosted AspNet WebAPI With Controller Classes I

2019-01-25 09:58发布

问题:

I have created a SelfHosted AspNet WebAPI with Visual Studio 2012 (.NET Framework 4.5). I enabled SSL for the WebAPI. It works fine when the controller is defined in the same project.

But when I add a reference of another project, containing controllers, it gives me the following error:

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

I have created custom classes for HttpSelfHostConfiguration and MessageHandler.

Any help to resolve this problem would be a great time-savor for me.

Thanking in advance.

回答1:

You can write a simple custom assemblies resolver which makes sure that your referenced assembly is loaded for the controller probing to work.

Following is a nice post from Filip regarding this:
http://www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/

Sample:

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;
    }
}