0

我正在尝试使用 Restsharp 将图像上传到 Microsoft 自定义视觉 API 预测端点,我正在尝试使用 AddFile 方法但我得到一个 BadRequest 作为结果,这是我正在使用的代码

public IRestResponse<PredictionResponse> Predict(string imageFileName)
    {
        var file = new FileInfo(imageFileName);
        var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
        var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
        var client = new RestClient(serviceUrl);
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/octet-stream");
        request.AddHeader("Prediction-Key", serviceKey);
        request.AddFile(file.Name, file.FullName);
        var response = client.Execute<PredictionResponse>(request);
        return response;
    }

当我执行该方法时,我从服务中得到以下响应

{
  "code": "BadRequestImageFormat",
  "message": "Bad Request Image Format, Uri: 1062fe0480714281abe2daf17beb3ac5"
}
4

1 回答 1

1

在restsharp文档中寻找正确上传文件的方法后,我找到了解决方案,它需要作为参数传递,参数类型为ParameterType.RequestBody的字节数组

这是实际有效的方法的示例

public IRestResponse<PredictionResponse> Predict(string imageFileName)
        {
            var file = new FileInfo(imageFileName);
            var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
            var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
            var client = new RestClient(serviceUrl);
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/octet-stream");
            request.AddHeader("Prediction-Key", serviceKey);
            request.AddParameter("content", File.ReadAllBytes(file.FullName), ParameterType.RequestBody);
            var response = client.Execute<PredictionResponse>(request);
            return response;
        }
于 2019-06-16T03:59:43.767 回答