ajax以GET和POST方式调用WCF(有参和无参)

废话不多说,以简单粗暴的方式展现出来。

一、第一步先添加一些必要代码,在实现类上面添加以下代码

//ajax请求要添加

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] //get请求要添加

配置文件web.config添加

<bindings>
      <!--get请求必须添加的-->
      <webHttpBinding>
        <binding name="webHttpBinding" crossDomainScriptAccessEnabled="true"/>
      </webHttpBinding>
    </bindings>

<services>
      <!--这里是发布的service,发布了ajax才能调用,调试的service不能出现在这里-->
      <service name="WcfTest.Service1" behaviorConfiguration="servicebehavior">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBinding"
          name="endpoint1" contract="WcfTest.IService1" behaviorConfiguration="NewBehavior0" />
      </service>
    </services>

最后还要添加一个Global.asax文件,这个post请求要用的,Application_BeginRequest方法添加以下代码

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");


                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }


二、ajax以GET请求调用WCF无参

1.在接口类里面添加一个方法

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string GetDataNoParams();

2.在实现类里面实现这方法

public string GetDataNoParams()
{
       return "hello world!";
}

3.js代码,地址改成自己的

function getWcfNoParams() {
$.ajax({
                url: "http://localhost:60570/Service1.svc/GetDataNoParams?jsoncallback=?",
                type: "GET",  
                contentType: "application/json",
                dataType: "json",
                processData: true,
                success: function(json) {
                alert("返回结果:"+json);
$("#write").text(json);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.status);
                    alert(textStatus);
                }
           });
}

二、ajax以GET调用WCF(有参)

1.在接口类里面添加一个方法

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string GetData(int value, string name);

2.在实现类里面实现这方法

public string GetData(int value, string name)
        {
            DataTable dt = new DataTable();
            dt.TableName = "Student";
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name");
            dt.Columns.Add("NickName");
            DataRow dr = dt.NewRow();
            dr["ID"] = value;
            dr["Name"] = name;
            dr["NickName"] = "小三";
            dt.Rows.Add(dr);

            string result = "";
            result = JsonConvert.SerializeObject(dt, new DataTableConverter());
            return result;
        }

3.js代码,地址改成自己的

function getWCF(value) {
$.ajax({
                url: "http://localhost:60570/Service1.svc/GetData?jsoncallback=?&value="+ value +"",
                type: "GET",  
                contentType: "application/json",
                dataType: "json",
                processData: true,
                success: function(json) {
                alert("返回结果:"+json);
$("#write").text(json);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.status);
                    alert(textStatus);
                }
            });
}

三、ajax以POST方式调用WCF(基本数据类型的参数)

1.在接口类里面添加一个方法

[OperationContract]
[WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string PostDataIntString(int value, string name);

2.在实现类里面实现这方法

public string PostDataIntString(int value, string name)
{
      string text = "我是{0},年龄{1}";
      return string.Format(text, name, value);
}

3.js代码,地址改成自己的

function postWCF_int_string(age,name) {
				$.ajax({
					type: "POST",
					url: "http://localhost:60570/Service1.svc/PostDataIntString",
					data: JSON.stringify({"value": age, "name": age,name}),
					contentType:"application/json;charset=utf-8",
		            dataType: 'json', 
					processData:true,
					success: function(json) {
						alert(json);
						$("#write").text(json);

					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert(XMLHttpRequest.status);
						alert(textStatus);
					}
				});
			}

四、ajax以POST方式调用WCF(参数是对象)

1.在接口类里面添加一个方法和一个类,参数是对象,不要BodyStyle

[OperationContract] // 参数是对象,不要BodyStyle
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string PostDataObject(CompositeType composite);

[DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";


        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

2.在实现类里面实现这方法

public string PostDataObject(CompositeType composite)
{     
     return composite.StringValue;
}

3.js代码,地址改成自己的

function postWCF_object() {
$.ajax({
type: "POST",
url: "http://localhost:60570/Service1.svc/PostDataObject",
data: JSON.stringify({"BoolValue": true, "StringValue": "json数据作为参数上传"}),
contentType:"application/json;charset=utf-8",
            dataType: 'json', 
processData:true,
success: function(json) {
alert(json);
$("#write").text(json);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}

五、另外顺便记录一下用C#的HttpWebRequest调用WCF代码

protected void btnSearch_Click(object sender, EventArgs e)
        {
            string url = "http://localhost:29851/shipping.svc/getShippingData";
            string contentTypeJson = "application/json;charset=utf-8";
            string jsonText = @"{""Department"": ""&&department"",""PageIndex"": 1,""PageSize"": 50}";
            jsonText = jsonText.Replace("&&department", department.SelectedValue);
            string text = PostHttp(url, jsonText, contentTypeJson);
        }

public string PostHttp(string url, string body, string contentType)
        {
            string responseContent = "";
          
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = contentType;
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 200000;

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();
            httpWebResponse.Close();

            return responseContent;
        }


代码地址


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值