私はRestSharp(Visual Studio 2013、.net 4.5でバージョン105.2.3.0)を使用して、NodeJSがホストするWebサービスを呼び出しています。私が作る必要がある呼び出しの1つは、ファイルをアップロードすることです。 RESTSharpリクエストを使用して、ストリームを最後からバイト配列に取得し、それをAddFileに渡すと正常に動作します。しかし、私はむしろ内容をストリーミングし、サーバーメモリ内のファイル全体をロードしないでください(ファイルのサイズは100 MBにすることができます)。RestSharp AddFileストリームを使用して
ストリームをコピーするアクションを設定すると(下記参照)、System.Net.ProtocolViolationExceptionの "MyStream.CopyTo"行で例外が発生します(ストリームに書き込まれるバイトはContent-Lengthを超えます)。指定されたバイトサイズ)。この例外は、client.Executeが呼び出された後のActionブロック内でスローされます。
私が読んだところでは、手動でContent-Lengthヘッダーを追加するべきではありません。私はCopyToバッファを小さな値と大きな値に設定しようとしました。まったく省略すると、無駄になります。誰かが私が逃したものについて私にヒントを与えることができますか?
// Snippet...
protected T PostFile<T>(string Resource, string FieldName, string FileName,
string ContentType, Stream MyStream,
IEnumerable<Parameter> Parameters = null) where T : new()
{
RestRequest request = new RestRequest(Resource);
request.Method = Method.POST;
if (Parameters != null)
{
// Note: parameters are all UrlSegment values
request.Parameters.AddRange(Parameters);
}
// _url, _username and _password are defined configuration variables
RestClient client = new RestClient(_url);
if (!string.IsNullOrEmpty(_username))
{
client.Authenticator = new HttpBasicAuthenticator(_username, _password);
}
/*
// Does not work, throws System.Net.ProtocolViolationException,
// Bytes to be written to the stream exceed the
// Content-Length bytes size specified.
request.AddFile(FieldName, (s) =>
{
MyStream.CopyTo(s);
MyStream.Flush();
}, FileName, ContentType);
*/
// This works, but has to load the whole file in memory
byte[] data = new byte[MyStream.Length];
MyStream.Read(data, 0, (int) MyStream.Length);
request.AddFile(FieldName, data, FileName, ContentType);
var response = client.Execute<T>(request);
// check response and continue...
}
私はちょうど同じ問題を発見しました。 'Request.AddFile(" file "、stream => data.CopyTo(stream)、fileName)' RestSharpバージョン105.2.0+で改行しました。 105.1.0にダウングレードすると正常に動作します。 git-repoの変更を調査する時間がまだありませんでした... – anve
私もこの問題があります。 105.1.0にダウングレードすると助けになりましたが、私は古い[githubに関する問題](https://github.com/restsharp/RestSharp/issues/70)にコメントを追加しました – Dmitry
AddFileBytesを使うことができます – hpfs