標籤:android ios wcf ws
簡單記錄一下使用實體物件作為參數的傳遞!
在服務端使用webservice時是沒有問題的,但是當替換成wcf時就出現傳遞的參數無法序列化的問題!
服務端代碼:
Service1.svc
namespace WcfTeacherService{ // 注意: 使用“重構”菜單上的“重新命名”命令,可以同時更改代碼、svc 和設定檔中的類名“Service1”。 // 注意: 為了啟動 WCF 測試用戶端以測試此服務,請在方案總管中選擇 Service1.svc 或 Service1.svc.cs,然後開始調試。 public class Service1 : IService1 { public string DoWork(TestModel model) { log4net.LogManager.GetLogger(this.GetType()).Error(model.AA); return model.AA; } }}
TestModel.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.ServiceModel;using System.Runtime.Serialization;namespace WcfTeacherService{ public class TestModel { public string AA { get; set; } }}
Android用戶端使用http://www.wsdl2code.com/pages/Home.aspx來自動產生所需要的代碼;調用如下:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Service1 service = new Service1();TestModel model = new TestModel();model.aA = "123";service.eventHandler = new IWsdl2CodeEvents() {@Overridepublic void Wsdl2CodeFinished(String methodName, Object Data) {@SuppressWarnings("unused")String aa = methodName;}@Overridepublic void Wsdl2CodeStartedRequest() {}@Overridepublic void Wsdl2CodeFinishedWithException(Exception ex) {}@Overridepublic void Wsdl2CodeEndedRequest() {}};try {service.DoWorkAsync(model);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}在WCF中以值類型作為參數,如:int,string,bool等都沒有問題,但是自訂實體物件作為參數時,總是擷取不到值!後來經過fiddler抓包反覆對比,原來是TestModel的命名空間和DoWork方法的命名空間不一致所致!
所以要修改上面的TestModel.cs;在類名上面加上命名空間的聲明
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.ServiceModel;using System.Runtime.Serialization;namespace WcfTeacherService{ [DataContract(Namespace="http://tempuri.org/")] public class TestModel { [DataMember] public string AA { get; set; } }}同時在介面上也加上相同的命名空間即可
namespace WcfTeacherService{ // 注意: 使用“重構”菜單上的“重新命名”命令,可以同時更改代碼和設定檔中的介面名“IService1”。 [ServiceContract(Namespace="http://tempuri.org/"] public interface IService1 { [OperationContract] string DoWork(TestModel model); }}
只要修改服務端的命名空間即可,ios和android端自動產生的程式碼無須變化!
記錄起來挺簡單的,就這麼簡單的問題可是調試了一天多呀!
Android/iOS訪問wcf傳遞參數為實體物件的問題