【发布时间】:2019-12-12 21:08:29
【问题描述】:
我正在尝试连接到我拥有 Postman Collection json 的 API:
{
"info": {
"_postman_id": "----",
"name": "Public API",
"description": "API",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Add Bim Info for a building",
"request": {
"auth": {
"type": "basic",
"basic": [
{
"key": "password",
"value": "somepassword",
"type": "string"
},
{
"key": "username",
"value": "someusername",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "file",
"type": "file",
"src": []
}
]
},
"url": {
"raw": "http://00.00.00.00:0000/api/apiName/building/",
"protocol": "http",
"host": [
"00",
"00",
"00",
"00"
],
"port": "0000",
"path": [
"api",
"apiName",
"building",
""
]
},
"description": "description"
},
"response": []
}
]
当我将此 json 加载到 postman 时,我可以毫无问题地发送文件,但我必须实现一个控制台程序才能做到这一点,所以我尝试使用 RestSharp 将邮递员集合转换为 c# 代码:
string filePath = @"path_to_file";
string url = "http://00.00.00.00:0000/api/apiName/building/";
string usr = "someuser";
string pwd = "somepassword";
RestClient client = new
RestClient(url);
client.Authenticator = new HttpBasicAuthenticator(usr, pwd);
RestRequest request = new RestRequest(url);
request.Method = Method.POST;
request.AddFile(Path.GetFileNameWithoutExtension(filePath), filePath);
try
{
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
Authenticator 工作正常,但是当我发送请求时,我收到消息: “所需的请求部分‘文件’不存在”
如何添加此请求? 我可以使用 json 作为模板来发送我的请求吗?
【问题讨论】:
-
使用像 wireshark 或 fiddler 这样的嗅探器,将 postman 结果与 c# 应用程序进行比较。检查标题以查看它们是否相同。如果没有,请让 c# 看起来完全像邮递员。通常这些错误是由于 c# 代码中的默认标头与邮递员不同。
-
邮递员会向您显示它发送的确切数据,请确保您匹配。
-
虽然我猜你需要做
request.AddFile("file", filePath); -
@DavidG 感谢您的评论,它也帮助了我...