当前位置:编程学习 > C#/ASP.NET >>

如何向wcf服务传递xml类型参数?前台为jquery ajax

现在前台能收到后台返回的xml数据,但是前台怎样传xml格式的参数到后台,后台又该怎么接收?
我用json传也传不过去,而我用json传输接收数据的时候都是正常的,现在接收数据类型改为xml后,
参数类型不管是json还是xml都不行了传不过去了,麻烦大家给看下,谢谢

以下是契约和实现:

契约
    [ServiceContract]
    [XmlSerializerFormat]
    public inte易做图ce ILog
    {

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        List<LoginResponseBDU> Login(string userid, string password);
    }

实现
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Log : ILog
    {
        public List<LoginResponseBDU> Login(string userid, string password)
        {
            LoginDAL loginDAL = new LoginDAL();
            List<LoginResponseBDU> ResponseList = new List<LoginResponseBDU>();
            int status = loginDAL.Login(userid, password, out ResponseList);
            return ResponseList;
        }
    }


以下是配置文件:


<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="wcftest.Log">
        <endpoint address="wcftest" kind="webHttpEndpoint" contract="wcftest.ILog" binding="webHttpBinding" bindingConfiguration="webHttpbinding"/>
      </service>
    </services>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="True"/>
      </webHttpEndpoint>
    </standardEndpoints>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpbinding" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
           为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 
          <serviceMetadata httpGetEnabled="true"/>
           要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>



以下是前台jquery代码:


            $.ajax({
                type: "GET",
                url: "http://172.168.1.10:1993/Service1.svc/wcftest/Login",
                dataType: "xml",
                contentType: "json",
                data: { "userid": 'mary', "password": '12345' },
                success: function (xml) {
                    $(xml).find('LoginResponseBDU').each(function () {
                        $strUser = $(this);
                        User = $strUser.find("autobusiness").text();
                    })
                    var detailUrl = "detail.html?id=" + User;
                    var html = "<tr><td>";
                    html += User + "</td><td>";
                    html += "<a href='" + detailUrl + "'>" + User + "</a></td><td>";
                    html += User + "</td><td>";
                    html += User + "</td></tr>";
                    $("#employees").append(html);
                    //                    });
                    $("#employees tr:odd").addClass("oddRow");
                }
            });
XML jQuery Ajax WCF  参数 json --------------------编程问答-------------------- LoginResponseBDU 有定义数据契约吗 --------------------编程问答-------------------- 有没有报啥错误 --------------------编程问答--------------------
引用 1 楼 u010383116 的回复:
LoginResponseBDU 有定义数据契约吗

有啊,只不过代码没贴出来,我用json的时候一切正常

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace ARTWcf.BusinessEntity.Login
{
    [DataContract]
    public class LoginRequestBDU
    {
        private string _userid = "";
        private string _password = "";
        private Int16 _deviceType;

        [DataMember]
        public string userid
        {
            get;
            set;
        }

        [DataMember]
        public string password
        {
            get;
            set;
        }

        [DataMember]
        public Int16 deviceType
        {
            get;
            set;
        }

        public LoginRequestBDU()
        {
 
        }
    }
}

--------------------编程问答--------------------
引用 2 楼 lixiaolian7 的回复:
有没有报啥错误

什么错误都没报,json的都能传参和返回值,xml的前台能接收返回数据,但是参数传不过去,我不知道xml应该如何传参,我这样写估计肯定是不对的 --------------------编程问答-------------------- 有没有高手帮看看? --------------------编程问答-------------------- 我照你的原文作了修改可以显示的哇,你对照看一下,如果还不能显示查看一下是不是跨域了,
namespace WcfService1
{
    [ServiceContract]   
    public inte易做图ce ILog
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)]
        List<LoginResponseBDU> Login(string userid, string password);
    }
    [DataContract]
    public class LoginResponseBDU
    {
        [DataMember]
        public string userid
        {
            get;
            set;
        }

        [DataMember]
        public string password
        {
            get;
            set;
        }

        [DataMember]
        public Int16 deviceType
        {
            get;
            set;
        }

       
    }


}

namespace WcfService1
{
 
  
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Log : ILog
    {
        public List<LoginResponseBDU> Login(string userid, string password)
        {
           // LoginDAL loginDAL = new LoginDAL();
            List<LoginResponseBDU> ResponseList = new List<LoginResponseBDU>();
          //  int status = loginDAL.Login(userid, password, out ResponseList);
            ResponseList.Add(new LoginResponseBDU() {userid=userid,password=password });
            return ResponseList;
        }
    }

}

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfService1.Log">
        <endpoint behaviorConfiguration="Ajaxor"  binding="webHttpBinding" contract="WcfService1.ILog"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="Ajaxor">
          <enableWebScript/>
        </behavior>       
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
          <serviceDebug includeExceptionDetailInFaults="true"/>  
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>  
</configuration>

jq
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">
</script>

</head>
 <script type="text/javascript">
        $(document).ready(function() {
            $('#GetUser').click(function() {

 $.ajax({
                 type: "get",
                  url: "http://localhost:31162/Service1.svc/Login",
                 data:"userid=user_sssaaa&password=bbbd",
  dataType: "xml",   
                   success: function (employees) {
     
  $(employees).find("LoginResponseBDU").each(function () {
                        $strUser = $(this);
                        User = $strUser.find("userid").text();
$("#showname").text("用户名:"+User);
                    })
                     
                  },
  error:function(a,b,c){alert(c);}
  
               });

            });
           
        });
   </script>
<body>

       <p id="GetUser">GetUser</p>
       <p id="showname" style="font-size:20px; background-color:#ffccff"> </p>
   
   
</body>
</html>

svc
<%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.Log" CodeBehind="Service1.svc.cs" %> --------------------编程问答-------------------- 跨域的话得在config里加 <webHttpBinding>
        <binding crossDomainScriptAccessEnabled="true" />
     </webHttpBinding>
--------------------编程问答-------------------- 如果你解决了,得给我加几分啊,因为刚才service name="WcfService1.Log"不小心写错调试了半个多小时 --------------------编程问答-------------------- 什么都没有错!!! 
就是错在直接使用 JSON 对象传递给服务方法:
正确做法是: 
    var newp = {};
    newp.id = 299;
    newp.first_name = "Sha";
    newp.last_name = "Zhang";
    newp.country = "USA";

    $.ajax({
        data: JSON.stringify(newp),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (req, tStatus) {
            alert(req);
        },
        type: "POST",
        url: "http://xxxxxxx/xxxxx"
    });
--------------------编程问答-------------------- 什么错误都没报,json的都能传参和返回值,xml的前台能接收返回数据,但是参数传不过去,我不知道xml应该如何传参,我这样写估计肯定是不对的 



一般XML网络间传值,如WS,或是WCF都建议BASE64后进行传。

补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,