c# - 使用邮递员集合连接到 Rest API
问题描述
我正在尝试连接到我有 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
我可以毫无问题地发送文件,但我必须实现一个控制台程序才能做到这一点,所以我尝试使用以下命令将邮递员集合转换为 c# 代码RestSharp
:
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 作为模板来发送我的请求吗?
解决方案
感谢@DavidG 的评论,这个问题得到了解答,我写了答案以使其成为官方。
RestRequest request = new RestRequest(url);
request.Method = Method.POST;
request.AddFile("file", filePath); //Changing this line generates the body in the json
推荐阅读
- javascript - 无法获取 React(不是 CORS)- 来自 Fetch API 的 POST 请求在浏览器中被取消
- python-3.x - 用列表替换多个字符串
- javascript - 一段时间后取消 requestAnimationFrame 循环
- binary-tree - 二叉树必须有数字节点吗?二叉树可以有一个带有字符串值的节点吗?
- excel - 将 Excel + 许多表单输入导入 Laravel 中的同一个 mysql 表
- typescript - 如何从其他类型中排除 {}?
- reactjs - 如何在 Reactjs 中将 CKEditor 用于数学公式和 MathJax
- php - Xampp Apache 服务器意外关闭
- numpy - 如何在numpy中对角化> 2d数组?
- google-chrome - Axios / Chrome:POST请求后出现意外的GET请求