Face API Base64图片帖子返回badrequest

时间:2016-10-30 01:49:49

标签: c# rest microsoft-cognitive

Face API与图片的网址一起使用,但是当我尝试将图片发送为时 Base64编码它返回一个错误。 在此示例代码中,我使用Restsharp发送数据

我的代码如下所示。

 public string GenerateRest(String Base64Image)
    {
        var serviceURL = Constants.BaseServiceURI;
        var client = new RestClient(serviceURL);

        var request = new RestRequest(Constants.BaseResoruce, Method.POST);
        request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
        request.AddHeader("Content-Type", "application/octet-stream");

        request.RequestFormat = DataFormat.Json;

        var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);

        byte[] newBytes = Convert.FromBase64String(baseString);

        request.AddBody(newBytes);
        // execute the request
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string

        return content;
    }

根据答案代码修复Restsharp请求后就像

 public FaceAPIOutput GenerateRest(String Base64Image)
    {
        var serviceURL = Constants.BaseServiceURI;
        var client = new RestClient(serviceURL);
        var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
        byte[] newBytes = Convert.FromBase64String(baseString);

        var request = new RestRequest(Constants.BaseResoruce, Method.POST);
        request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
        request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
        request.RequestFormat = DataFormat.Json;

        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string

        return ConvertToFaceAPIOutObject(content);
    }

1 个答案:

答案 0 :(得分:2)

Restsharp在获取二进制有效负载时看起来有点特殊。而不是request.AddBody,它添加了一个多部分表单部分,您需要执行以下操作:

request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);

c.f。 Can RestSharp send binary data without using a multipart content type?