【问题标题】:Passing parameters to WEB API Self Hosted Service将参数传递给 WEB API 自托管服务
【发布时间】:2015-08-10 01:29:41
【问题描述】:

我有一个简单的客户端应用程序,它与自托管的 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();
        }
    }

【问题讨论】:

  • 服务器如何期望这些字符串?请求参数? JSON 对象?还有什么?
  • 这是一个自托管的 web api,客户端是一个控制台应用程序。上面我会添加WEB API Service的main方法。
  • 我的意思是,您尝试发送的值是什么?控制器希望如何接收这些值?
  • 我想发送连接字符串信息。我不确定控制器将如何接收该值。这是我的问题的一部分。
  • 这听起来越来越像是一个关于如何使用 WebAPI 的非常广泛的问题......你的控制器是什么样的? WebAPI 代码在哪里使用需要发送给它的值?

标签: c# self-hosting


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 2011-01-23
    • 1970-01-01
    • 2015-07-10
    • 2014-07-20
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多