将参数传递给WEB API自托管服务

时间:2015-05-27 19:20:30

标签: c# self-hosting

我有一个简单的客户端应用程序与自托管的Web API进行对话:

class Program
{
    static HttpClient client = new HttpClient();
    static void Main(string[] args)
    {
        client.BaseAddress = new Uri("http://localhost:8080");

        LoadForeman();

        Console.WriteLine("Press Enter to quit.");
        Console.ReadLine();
    }

    static void LoadForeman()
    {
        HttpResponseMessage resp = client.GetAsync("api/foreman").Result;
        resp.EnsureSuccessStatusCode();

        var foreman = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Foreman>>().Result;
        foreach (var f in foreman)
        {
            Console.WriteLine("{0} {1}", f.ForeBadge, f.ForeName);
        }
    }
}

如何将参数(字符串)从客户端传递到服务?

编辑:WEB API服务

    static void Main(string[] args)
    {
        var config = new HttpSelfHostConfiguration("http://localhost:8080");
        //describes how to access API via HTTP
        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

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

            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }
    }

1 个答案:

答案 0 :(得分:1)

我意识到这是一篇旧帖子,但您可以使用自定义DelegatingHandler将信息传递给控制器​​。

即:

 _config = New HttpSelfHostConfiguration(myUrl)
 _config.MessageHandlers.add(New MyHandler(cs))

Public Class WebApiHandler
    Inherits System.Net.Http.DelegatingHandler
    Private ReadOnly _cs As String
    Public Sub New(ByVal cs as String)
        _cs = cs
    End Sub

    Protected Overrides Function SendAsync(request As HttpRequestMessage, cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
        request.Properties("ConnectionString") = _cs
        Return MyBase.SendAsync(request, cancellationToken)
    End Function
End Class