【问题标题】:Calling a REST API on a .NETCore server在 .NET Core 服务器上调用 REST API
【发布时间】:2018-11-09 17:37:47
【问题描述】:

我不是 linux 专家,使用 curl 对我来说太复杂了。所以我找到了 httpie 并尝试调用我自己用 C# 编写的 REST 服务器之一,针对 .NETCore 2 并在 CentOS 7 下的 Docker 上运行。

我在 Windows 上有一个可用的 Powershell 脚本,并尝试使用 httpie 将其移植到 bash 脚本,不幸的是没有运气。

API 在服务器上生成一个文件并将其返回为octet-stream。服务端的headers定义如下:

        Options = new Dictionary<string, string>
        {
            {"Content-Type", "application/octet-stream"},
            {"X-Api-DocType", filetype},
            {"X-Api-DocLength", responseStream.Length.ToString()}
        };

我的 POWERSHELL 脚本(运行良好)如下所示:

$request = @{
    Namespace = "MyApplication.MessagingApi"
    Version = "current"
    DataDefinitionLanguage = "Csharp"
    MakePartial = $false
    MakeVirtual = $false
}
$docPath = "D:\Projects\AccountingApiMessageDefinitions.cs"
$Url = "http://172.16.63.241:6083/bbopman/messaging/apireferences"
$response = Invoke-WebRequest -Method Get -Uri $Url -Body $request
Set-Content -Path $docPath -Encoding Byte -Value $response.Content

我将此移植到bash 脚本,如下所示:

#!/bin/bash
url="http://172.16.63.241:6083/bbopman/messaging/apireferences"
request="Namespace=='MyApplication.MessagingApi' Version=='current' DataDefinitionLanguage=='Csharp'"
http -d GET $url $request > ~/AccountingApiMessageDefinitions.cs

我得到的是 BAD REQUEST 但在服务器上调用已成功处理。所以我想我在阅读响应时出错了,但不知道是什么......这是我的shell中的输出:

$ ./ExecuteRestCall.sh 
HTTP/1.1 400 Bad Request
Content-Type: text/html
Date: Wed, 30 May 2018 18:45:50 GMT
Server: Kestrel
Transfer-Encoding: chunked
Vary: Accept
X-Powered-By: ServiceStack/5.02 NETStandard/.NET

谁能告诉我如何正确地从 Linux shell 调用它?非常感谢。

【问题讨论】:

    标签: bash httpie


    【解决方案1】:

    httpie 的参数值不需要引号。不带引号发送。

    request="Namespace==MyApplication.MessagingApi Version==current DataDefinitionLanguage==Csharp"
    

    此外,您似乎缺少 shell 脚本版本中的 MakePartialMakeVirtual 参数。

    顺便说一句:“在服务器上成功处理了呼叫” - 这不可能是真的。错误的请求状态是由服务器返回的,而不是在客户端发生的。

    【讨论】:

    • 我没有调试它,只是查看控制台输出。它看起来正确,但实际上是错误的:Request starting HTTP/1.1 GET http://172.16.63.241:6083/bbopman/messaging/apireferences?Version=%27current%27&amp;Namespace=%27MyAppli...%27' 的转义码,而 PS 版本中不存在这种代码……MakePartialMakeVirtial 如果未设置,则默认为 false,所以这是正确的。我只需要删除引号就可以了!谢谢!
    猜你喜欢
    • 2019-12-20
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多