asp.net-web-api – 在LINQPad中使用WebAPI?

前端之家收集整理的这篇文章主要介绍了asp.net-web-api – 在LINQPad中使用WebAPI?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试在LINQPad中使用Selfhosted WebAPI时,我只是不断收到与该类的控制器不存在相同的错误.

我必须为WebAPI(控制器/类)创建单独的程序集,然后在我的查询中引用它们吗?

这是我正在使用的代码

#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();
    }
}

在VS2012中的单独控制台项目中,此代码工作正常.

当我没有得到“正常”WebAPI路由工作时,我通过NuGET开始使用AttributeRouting.

浏览器中出现的错误是:没有找到符合请求URI’http://192.168.0.196:8181/players/allPlayers’的HTTP资源.

附加错误:没有找到与名为“PlayerObject”的控制器匹配的类型

解决方法

默认情况下,Web API将忽略不公开的控制器,LinqPad类是公共的,我们在 scriptcs中也有类似的问题

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

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

所以,添加

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

}

然后注册你的配置,你完成了:

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

这是一个完整的工作示例,我刚刚对LinqPad进行了测试.请注意,您必须以管理员身份运行LinqPad,否则您将无法在端口上侦听.

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();
    };
}
原文链接:https://www.f2er.com/aspnet/250581.html

猜你在找的asp.Net相关文章