加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – SelfHosted AspNet WebAPI与不同项目中的控

发布时间:2020-12-15 20:13:52 所属栏目:asp.Net 来源:网络整理
导读:我已经使用Visual Studio 2012(.NET Framework 4.5)创建了一个SelfHosted AspNet WebAPI.我启用了WebAPI的SSL.当控制器在同一个项目中定义时,它工作正常. 但是当我添加另一个包含控制器的项目的引用时,它给我以下错误: No HTTP resource was found that mat
我已经使用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创建了自定义类.

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

提前感谢

解决方法

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

以下是Filip的一个很好的帖子:
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:libscontrollersControllersLibrary.dll");

        baseAssemblies.Add(controllersAssembly);

        return assemblies;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读