wcf在post请求的各种处理方式

一、方法默认只有一个参数

(1)BodyStyle = WebMessageBodyStyle.Bare

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[Description("地址解析(多个地址以','间隔,解析结果以JSON格式返回)")]
string Parse(string address);

------------------------------------------------------------------------------------

c#代码在客户端调用时,使用以下语句:

//SufeiHttpHelper是一个第三方的http请求调用工具

SufeiHttpHelper helper = new SufeiHttpHelper();
var item = new HttpItem();
item.URL = "http://localhost:35401/parse";
item.ContentType = "application/json";
item.Method = "post";
item.PostEncoding = Encoding.GetEncoding("utf-8");
item.Postdata = "\"天津大学\"";

(2)BodyStyle = WebMessageBodyStyle.Wrapped

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
[Description("地址解析(多个地址以','间隔,解析结果以JSON格式返回)")]
string Parse(string address);

---------------------------------------------------------------------------------------

item.PostEncoding = Encoding.GetEncoding("utf-8");

item.Postdata = "{\"address\":\"天津\"}";             //包装成json格式,并且指定参数名称

总结:以上两个形式,在传入string参数为中文时,必须要包装成json,如果是数字或字母,在BodyStyle = WebMessageBodyStyle.Bare),可以直接传入,无需包装成json

 

二、方法有多个参数

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped)]
Stream HelloDataStr(String data1,string data2);

由于是多个参数,BodyStyle必须为 WebMessageBodyStyle.Wrapped,否则参数无法映射。

客户端调用:

item.PostEncoding = Encoding.GetEncoding("utf-8");

item.Postdata = {\"data1\":\"hh\",\"data2\":\"ss\"}");

三、使用rest风格的url

[OperationContract]
[WebInvoke(Method="POST",ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,UriTemplate ="Delete/{keyword}")]
[Description("删除无效IP")]
string DeleteKeyword(string keyword);

客户端调用:

var url = "http://localhost:24320/delete/中国";
item.Method = "post";   

//无需再使用item.postdata语句

四、参数通过WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters传递

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "FileToBase64String")]
[Description("将文件转换成base64字符,一个参数:filename,表示文件的全路径")]
string FileToBase64String();

在服务端通过var filename = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["filename"]获取参数

这种方式的POST请求代码如下:

item.Method = "POST";
item.URL = "http://localhost:50887/FileToBase64String?filename=N:\\广东\\标定地价查询系统操作指南.doc";

 五、wcf如何上传文件?

前端或c#客户端通过将要上传的文件转换成base64字符,然后通过json传到WCF服务端,详见ArcEngineWcfService中的UploadFile方法。

(一)、wcf端代码

1、接口定义

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "UploadFile")]
[Description("上传文件,两个参数:base64是文件转换后的base64字符串,filename是上传后的文件名,例如:工业用地.rar")]
string UploadFile();

2、服务端实现

 1             try
 2             {
 3                 var message = OperationContext.Current.RequestContext.RequestMessage;
 4                 var mes = message.ToString();
 5                 var doc = new XmlDocument();
 6                 doc.LoadXml(mes);
 7                 var json = doc.DocumentElement.InnerText;
 8                 JObject jo = null;
 9                 try
10                 {
//postman前端调用,传过来的是json格式,可以直接转换
11 jo = JObject.Parse(json); 12 base64 = jo["base64"].ToString(); 13 filename = jo["filename"].ToString(); 14 } 15 catch (Exception) 16 { 17 //由于C#客户端调用传过来的是xml格式,无法直接转换成json,只能使用XML格式获取参数值 18 var nodes = doc.DocumentElement.ChildNodes; 19 foreach (XmlNode node in nodes) 20 { 21 var name = node.Name.ToString(); 22 if (name=="base64") 23 { 24 base64 = node.InnerText; 25 } 26 else if (name=="filename") 27 { 28 filename = node.InnerText; 29 } 30 } 31 } 32 } 33 catch (Exception ex) 34 { 35 try 36 { 37 base64 = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["base64"]; 38 filename = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["filename"]; 39 } 40 catch (Exception) 41 { 42 } 43 }

(二)客户端调用服务

1、postman调用

(1)如果是不长的参数,建议使用params方式调用

http://localhost:50887/UploadFile?base64=a&filename=b

(2)如果是长字符串,使用body中的raw方式,参数格式为json

2、C#客户端调用

(1)使用WebClient

                WebClient webClient = new WebClient();
                webClient.Headers = new WebHeaderCollection();
                webClient.Headers.Add("Content-Type", "application/json");
                if (method.ToLower().Equals("get"))
                {
                    byte[] bytes = webClient.DownloadData(url);
                    return System.Text.Encoding.UTF8.GetString(bytes);
                }
                if (method.ToLower().Equals("post"))
                {
                    byte[] bytes = webClient.UploadData(url, System.Text.Encoding.UTF8.GetBytes(entity));
                    return System.Text.Encoding.UTF8.GetString(bytes);
                }
                if (method.ToLower().Equals("delete"))
                {
                    webClient.Encoding = Encoding.UTF8;    //TODO:json中有中文,必须要设置编码为utf-8,否则会报400错误
                    return webClient.UploadString(url, "DELETE", entity);
                }

//调用以上方法
                 
var json = "{\"base64\":\"aa\",\"filename\":\"中国.doc\"}";

                RequestByJSON("http://localhost:50887/uploadfile", "post", json);
 

(2)使用苏飞httphelper

            var http = new HttpHelper();
            var item = new HttpItem();
            item.Method = "post";
            item.ContentType = "application/json";
            item.URL = "http://localhost:50887/uploadfile";
            var o = new { base64 = "a", filename = "中国.doc" };
            item.Postdata = JsonConvert.SerializeObject(o);
            //参数中有中文,必须使用utf-8编码,否则服务端收到的消息是乱码
            item.PostEncoding = Encoding.GetEncoding("UTF-8");
            var html = http.GetHtml(item).Html;

 

posted @ 2018-11-10 02:11  SimpleGIS  阅读(1500)  评论(0编辑  收藏  举报