简体   繁体   English

将参数传递给WEB API自助服务

[英]Passing parameters to WEB API Self Hosted Service

I have a simple client app that talks to a self hosted web api: 我有一个简单的客户端应用程序,可与自托管的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);
        }
    }
}

How do I pass parameters (strings) from the client to the service? 如何将参数(字符串)从客户端传递到服务?

EDIT: WEB API SERVICE 编辑: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();
        }
    }

I realize that this is an old post, but you can pass information to the controller with a custom DelegatingHandler. 我意识到这是一个老帖子,但是您可以使用自定义DelegatingHandler将信息传递给控制器​​。

ie: 即:

 _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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM