c# - 添加更多参数时,RestSharp Azure Web API 调用失败
问题描述
我正在尝试使用 RestSharp 调用 Azure 计算机视觉 API,特别是 [POST] Batch Read File。在下面的代码中一切正常:
private void MakeBatchReadRequest(string imageFilePath)
{
try
{
RestClient client = new RestClient("https://southeastasia.api.cognitive.microsoft.com/");
client.AddDefaultHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
RestRequest request = new RestRequest("vision/v2.0/read/core/asyncBatchAnalyze", Method.POST);
request.AddHeader("Content-Type", "application/octet-stream");
byte[] byteData = GetImageAsByteArray(imageFilePath);
request.AddParameter("application/octet-stream", byteData, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
operationLocation = response.Headers.Where(x => x.Name == "Operation-Location").First.Value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我不必包含参数mode
,因为根据这里看到的 API 文档,它是可选的,默认值是Printed
我想要的。但是,如果我在请求中添加参数mode
(以防万一我改变主意并切换到其他内容),如下所示:
private void MakeBatchReadRequest(string imageFilePath)
{
try
{
RestClient client = new RestClient("https://southeastasia.api.cognitive.microsoft.com/");
client.AddDefaultHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
RestRequest request = new RestRequest("vision/v2.0/read/core/asyncBatchAnalyze", Method.POST);
request.AddHeader("Content-Type", "application/octet-stream");
byte[] byteData = GetImageAsByteArray(imageFilePath);
request.AddParameter("application/octet-stream", byteData, ParameterType.RequestBody);
request.AddParameter("mode", "Printed") // This will cause the web API to return an error response.
RestResponse response = client.Execute(request);
operationLocation = response.Headers.Where(x => x.Name == "Operation-Location").First.Value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
API 返回响应状态码415
和状态描述Unsupported Media Type
。整个 JSON 响应如下:
{
"error": {
"code": "BadArgument",
"message": "Unsupported media type."
}
}
我不太确定向请求中添加简单参数如何触发 API 的错误响应。另外我不确定为什么会出现错误响应,Unsupported Media Type
因为我正在使用JPG
受支持的图像文件并将其内容类型设置为application/octet-stream
请求中的内容。
任何帮助将不胜感激。
解决方案
我升级到 .Net Framework 4.6.1 版和 RestSharp 106.6.9 版,现在可以正常工作了。我想我别无选择,只能升级我的应用程序的 .Net Framework 版本,这样我就可以使用更新且错误更少的 RestSharp 版本。
推荐阅读
- asp.net-core - 用户身份角色
- file-upload - Fetch API 将损坏的 Excel 文件上传到 Dropbox
- javascript - 使用 Javascript 的动画 SVG 徽标
- python - python中出现错误时如何运行函数
- hibernate - 我可以在调用返回结果集但也更新行的存储过程的方法上使用@Transactional(readOnly = true) 吗?
- html - 如何使用 Bootstrap 5 使导航栏背景颜色宽度大小与导航栏内容对齐
- exchange-server - 内容问题将文件夹移动到其他驱动器
- vue.js - 想安装 vue 3,现在没有任何效果
- python - Pandas 读取 sharepoint excel 文件:XLRDError
- python - 具有多个蓝图路由文件的 Flask 应用程序