在LINQPad使用的WebAPI? [英] Using WebAPI in LINQPad?

查看:230
本文介绍了在LINQPad使用的WebAPI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图用Selfhosted的WebAPI在LINQPad,我只是不断地得到同样的错误,对于该类的控制器不存在。

When I tried to use the Selfhosted WebAPI in LINQPad, I just kept getting the same error that a controller for the class didn't exist.

我必须为的WebAPI创建单独的组件(控制器/班),然后在我的查询中引用它们?

Do I have to create separate assemblies for the WebAPI (Controllers/Classes) and then reference them in my query?

这里的code我用

#region namespaces
using AttributeRouting;
using AttributeRouting.Web.Http;
using AttributeRouting.Web.Http.SelfHost;
using System.Web.Http.SelfHost;
using System.Web.Http.Routing;
using System.Web.Http;
#endregion

public void Main()
{

    var config = new HttpSelfHostConfiguration("http://192.168.0.196:8181/");
    config.Routes.MapHttpAttributeRoutes(cfg =>
    {
        cfg.AddRoutesFromAssembly(Assembly.GetExecutingAssembly());
    });
    config.Routes.Cast<HttpRoute>().Dump();

    AllObjects.Add(new UserQuery.PlayerObject { Type = 1, BaseAddress = "Hej" });

    config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    using(HttpSelfHostServer server = new HttpSelfHostServer(config))
    {
        server.OpenAsync().Wait();
        Console.WriteLine("Server open, press enter to quit");
        Console.ReadLine();
        server.CloseAsync();
    }

}

public static List<PlayerObject> AllObjects = new List<PlayerObject>();

public class PlayerObject
{
    public uint Type { get; set; }
    public string BaseAddress { get; set; }
}

[RoutePrefix("players")]
public class PlayerObjectController : System.Web.Http.ApiController
{
    [GET("allPlayers")]
    public IEnumerable<PlayerObject> GetAllPlayerObjects()
    {
        var players = (from p in AllObjects
                    where p.Type == 1
                    select p);
        return players.ToList();
    }
}

这code正常工作在一个单独的控制台项目在VS2012的时候。

This code works fine when in a separate Console Project in VS2012.

我开始使用通过的NuGet AttributeRouting时,我没得到正常的WebAPI路由工作。

I started using AttributeRouting via NuGET when I didn't get the "normal" WebAPI-routing to work.

我在浏览器中得到的错误是:无HTTP资源发现,请求URI'匹配http://192.168.0.196:8181/players/allPlayers'.

The error I got in the browser was: No HTTP resource was found that matches the request URI 'http://192.168.0.196:8181/players/allPlayers'.

其他错误:没有类型,发现名为PlayerObject控制器匹配

推荐答案

默认的Web API将忽略控制器是不公开的,LinqPad类的嵌套公共的,我们也有类似的问题,在<一个HREF =htt​​ps://github.com/scriptcs/相对=nofollow> scriptcs

Web API by default will ignore controllers that are not public, and LinqPad classes are nested public, we had similar problem in scriptcs

您必须添加自定义控制器解析,这将绕过限制,并允许您从执行的程序集手动发现控制器类型。

You have to add a custom controller resolver, which will bypass that limitation, and allow you to discover controller types from the executing assembly manually.

这实际上是已经固定的(现在的Web API控制器只需要的可见的不公开),但发生在九月和自我主机的最新的稳定版本是从八月。

This was actually fixed already (now Web API controllers only need to be Visible not public), but that happened in September and the latest stable version of self host is from August.

所以,补充一点:

public class ControllerResolver: DefaultHttpControllerTypeResolver {

    public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) {
        var types = Assembly.GetExecutingAssembly().GetExportedTypes();
        return types.Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList();
    }

}

然后注册对你的配置,你就大功告成了:

And then register against your configuration, and you're done:

var conf = new HttpSelfHostConfiguration(new Uri(address));
conf.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver());

下面是一个完整的工作的例子,我只是测试对LinqPad。请注意,您必须运行LinqPad作为管理员,否则你将无法在一个端口监听。

Here is a full working example, I just tested against LinqPad. Note that you have to be running LinqPad as admin, otherwise you won't be able to listen at a port.

public class TestController: System.Web.Http.ApiController {
    public string Get() {
        return "Hello world!";
    }
}

public class ControllerResolver: DefaultHttpControllerTypeResolver {
    public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver) {
        var types = Assembly.GetExecutingAssembly().GetExportedTypes();
        return types.Where(x => typeof(System.Web.Http.Controllers.IHttpController).IsAssignableFrom(x)).ToList();
    }
}

async Task Main() {
    var address = "http://localhost:8080";
    var conf = new HttpSelfHostConfiguration(new Uri(address));
    conf.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver());

    conf.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    var server = new HttpSelfHostServer(conf);
    await server.OpenAsync();

    // keep the query in the 'Running' state
    Util.KeepRunning();
    Util.Cleanup += async delegate {
        // shut down the server when the query's execution is canceled
        // (for example, the Cancel button is clicked)
        await server.CloseAsync();
    };
}

这篇关于在LINQPad使用的WebAPI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆