2012-07-27 59 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