10 c# rest restsharp servicestack
我希望能够发布一个文件,并作为该帖子的一部分添加数据.
这是我有的:
var restRequest = new RestRequest(Method.POST);
restRequest.Resource = "some-resource";
restRequest.RequestFormat = DataFormat.Json;
string request = JsonConvert.SerializeObject(model);
restRequest.AddParameter("text/json", request, ParameterType.RequestBody);
var fileModel = model as IHaveFileUrl;
var bytes = File.ReadAllBytes(fileModel.LocalStoreUrl);
restRequest.AddFile("FileData", bytes, "file.zip", "application/zip");
var async = RestClient.ExecuteAsync(restRequest, response =>
{
if (PostComplete != null)
PostComplete.Invoke(
new Object(),
new GotResponseEventArgs
<T>(response));
});
Run Code Online (Sandbox Code Playgroud)
它发布文件很好,但数据不存在 - 这甚至可能吗?
[UPDATE]
我修改了代码以使用多部分标题:
var restRequest = new RestRequest(Method.POST);
Type t = GetType();
Type g = t.GetGenericArguments()[0];
restRequest.Resource = string.Format("/{0}", g.Name);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddHeader("content-type", "multipart/form-data");
string request = JsonConvert.SerializeObject(model);
restRequest.AddParameter("text/json", request, ParameterType.RequestBody);
var fileModel = model as IHaveFileUrl;
var bytes = File.ReadAllBytes(fileModel.LocalStoreUrl);
restRequest.AddFile("FileData", bytes, "file.zip", "application/zip");
var async = RestClient.ExecuteAsync(restRequest, response =>
{
if (PostComplete != null)
PostComplete.Invoke(
new Object(),
new GotResponseEventArgs
<T>(response));
});
Run Code Online (Sandbox Code Playgroud)
仍然没有运气......任何指针?
我不确定这是否有帮助。但请尝试一下。
由于您尝试将其作为 text/json 传递,因此您可以尝试将字节数组转换为字符串并将其添加到请求中。
要将其转换为字符串,您可以执行类似的操作。
public string ContentsInText
{
get
{
return Encoding.Default.GetString(_bytecontents);
}
}
Run Code Online (Sandbox Code Playgroud)
要将其转换为字节数组,您可以这样做。您很可能必须在网络服务中执行此操作。
public byte[] ContentsInBytes
{
get { return Encoding.Default.GetBytes(_textcontents); }
}
Run Code Online (Sandbox Code Playgroud)