2017-05-20 3 views
2

클라이언트입니다 :지원되지 않는 미디어 유형 POST는 웹 API에 여기

using (var client = new HttpClient()) 
{ 

    client.BaseAddress = new Uri("http://localhost/MP.Business.Implementation.FaceAPI/"); 
    client.DefaultRequestHeaders 
      .Accept 
      .Add(new MediaTypeWithQualityHeaderValue("application/octet-stream")); 
    using (var request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress + "api/Recognition/Recognize")) 
    { 
     request.Content = new ByteArrayContent(pic); 
     request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); 

     await client.PostAsync(request.RequestUri, request.Content); 

    } 
} 

서버 :

[System.Web.Http.HttpPost] 
public string Recognize(byte[] img) 
{ 
    //do someth with the byte [] 

} 

나는 점점 오전 오류 :

415 Unsupported Media Type

항상 - 요청 엔터티의 미디어 pe 'application/octet-stream'은이 자원에서 지원되지 않습니다. 그것에 대해 무엇을 할 수 있습니까? 내가 여기에 몇 가지 답변 스레드를 찾았지만, 그것은 도움이되지 않았다.

답변

0

application/octet-stream 데이터를 나타내는 가장 좋은 방법이지만 웹 API에서는 기본값이 아닙니다.

내 해결 방법은 ASP.NET Core 1.1 - 다른 변형이 다른 경우 일 수 있습니다.

컨트롤러 방법에서 img 매개 변수를 제거하십시오. 대신 StreamRequest.Body을 참조하십시오. 예 : 파일에 저장하려면

using (var stream = new FileStream(someLocalPath, FileMode.Create)) 
{ 
    Request.Body.CopyTo(stream); 
} 

GET 컨트롤러 메서드에서 이진 데이터를 반환하는 경우와 비슷한 상황이 발생합니다. 반환 유형을 byte[]으로하면 base64로 포맷됩니다! 이로 인해 상당히 커집니다. 최신 브라우저는 원시 이진 데이터를 완벽하게 처리 할 수 ​​있으므로 더 이상 적절한 기본값이 아닙니다.

Response.ContentType = "application/octet-stream"; 
Response.Body.Write(myArray, 0, myArray.Length); 

컨트롤러 방법 void의 반환 유형을 확인하십시오

는 다행히도 Response.Bodyhttps://github.com/danielearwicker/ByteArrayFormatters이 있습니다.

UPDATE는

나는 컨트롤러 방법에 byte[] 직접 사용할 수있는 nuget 패키지를 만들었습니다. 참조 : https://github.com/danielearwicker/ByteArrayFormatters

관련 문제