2012-07-27 79 views
0

任何人都可以解決這個問題我有兩個相同的服務差不多,但是一個更新完成後,一個請求失敗?問題與兩個相同的服務

​​

這是工作合同:

[OperationContract] 
    [WebInvoke(Method = "PUT", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/UpdateCarType/{carregistration}")] 
    void UpdateCarType(string carregistration, CarType cartype); 

這是客戶端更新和get請求:

更新:

private void button29_Click(object sender, RoutedEventArgs e) 
    { 
     string uriupdatestaff = string.Format("http://localhost:8002/Service/UpdateCarType/{0}", textBox30.Text); 
     StringBuilder sb = new StringBuilder(); 
     sb.Append("<CarType>"); 
     sb.AppendLine("<CarRegistration>" + textBox30.Text + "</CarRegistration>"); 
     sb.AppendLine("<CarColour>" + this.comboBox6.Text + "</CarColour>"); 
     sb.AppendLine("<CarEngineSize>" + this.comboBox7.Text + "</CarEngineSize>"); 
     sb.AppendLine("</CarType>"); 
     string NewStudent = sb.ToString(); 
     byte[] arr = Encoding.UTF8.GetBytes(NewStudent); 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uriupdatestaff); 
     req.Method = "PUT"; 
     req.ContentType = "application/xml"; 
     req.ContentLength = arr.Length; 
     Stream reqStrm = req.GetRequestStream(); 
     reqStrm.Write(arr, 0, arr.Length); 
     reqStrm.Close(); 
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     MessageBox.Show(resp.StatusDescription); 
     reqStrm.Close(); 
     resp.Close(); 
    } 

得到:

{ 
     string uriGetdates = "http://localhost:8002/Service/CarType"; 
     XDocument xDoc = XDocument.Load(uriGetdates); 
     var dates = xDoc.Descendants("CarType") 
      .Select(n => new 
      { 
       CarRegistration = n.Element("CarRegistration").Value, 
       CarModel = n.Element("CarModel").Value, 
       CarMake = n.Element("CarMake").Value, 
       CarColour = n.Element("CarColour").Value, 
       CarEngineSize = n.Element("CarEngineSize").Value, 
       CostPerDay = n.Element("CarHireCostPerDay").Value, 
      }) 
      .ToList(); 
     dataGrid10.ItemsSource = dates; 
    } 

我的自動想法是因爲即時只定義汽車顏色和汽車發動機大小,其餘的字段爲空,但完全相同的操作,但與客戶不這樣做,它將列表返回到數據網格即使我只更新一個字段。

當我嘗試重新更新cartype時,得到的錯誤是Object reference not set to an instance of an object.

+2

其中abouts是拋出的錯誤? – Chris 2012-07-27 09:03:30

+1

你稱之爲小:P – albertjan 2012-07-27 09:14:53

+0

在使用它之前,你還沒有初始化一個變量 - 調試,它會告訴你它在哪一行上,因此要修復哪一行。 – Bridge 2012-07-27 09:17:32

回答

1

當您更新,你不設置CarModelCarMake什麼...

所以我看不出你如何能找回它們。

爲了避免錯誤,沒有管理的實際問題,你需要null檢查:

CarRegistration = n.Element("CarRegistration")!= null ? n.element("CarRegistration").Value : string.Empty, 
       //etc. 

順便說一句,你可以使用Xml.Linq語法,而不是一個StringBuilder來寫你的XML!

var car = new XElement("CarType"); 
car.Add(new XElement("CarRegistration"), textBox30.Text); 
//etc. 
var NewStudent = car.ToString();//NewStudent for a car, weird ;) 
+0

謝謝,不知道爲什麼我在想更新只更新了請求的字段。 Bahhh! – 2012-07-27 14:33:12

相關問題