首页 > 解决方案 > 添加更多参数时,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请求中的内容。

任何帮助将不胜感激。

标签: c#jsonrestrestsharpazure-cognitive-services

解决方案


我升级到 .Net Framework 4.6.1 版和 RestSharp 106.6.9 版,现在可以正常工作了。我想我别无选择,只能升级我的应用程序的 .Net Framework 版本,这样我就可以使用更新且错误更少的 RestSharp 版本。


推荐阅读