这是我的情景: 我有一个Rest服务,它在查询部分中有一个字符串参数,它将被反序列化为包含byte []的复杂对象:
[OperationContract]
[WebInvoke(Method = "PUT",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json?doc={doc}")]
string UploadDocument(string doc);
这是我的UploadDocument继承:
public string UploadDocument(string doc)
{
if(string.IsNullOrEmpty(doc))
return "ko";
JavaScriptSerializer jscript = new JavaScriptSerializer();
Document inputDocument = jscript.Deserialize<Document>(doc);
return "ok";
}
我需要从客户端调用它来读取文件的内容并将其放在参数中:
JavaScriptSerializer jscript = new JavaScriptSerializer();
Document newComp = jscript.Deserialize<Document>(test);
newComp.Content = File.ReadAllBytes(@"D:\Test\PdfParse\test.pdf");
newComp.filename = "test.pdf";
test = jscript.Serialize(newComp);
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(test);
WebRequest request = WebRequest.Create("http://localhost/DocumentUpload/DocumentUpload.svc/json?doc=");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
WebResponse wr = request.GetResponse();
using (StreamReader sw = new StreamReader(wr.GetResponseStream()))
{
test = (sw.ReadToEnd());
}
问题 如果我在WebRequest.Create中添加“test”内容,则url太长,但将其写入requestStream rest服务返回给我“doc”始终为空。 我可以通过哪种方式传递参数?
答案 0 :(得分:0)
您可以在方法中使用multipart_form_data媒体类型。 在这种情况下,您可以直接将流传递给您的代码。
我认为此链接可以帮助您: http://www.briangrinstead.com/blog/multipart-form-post-in-c
祝你好运