سؤال

أنا أستخدم خدمة الويب الثالثة التي تقدم المكالمات والردود التالية

http://api.athirdparty.com/rest/foo?apikey=1234

<response>
  <foo>this is a foo</foo>
</response>

و

http://api.athirdparty.com/rest/bar?apikey=1234

<response>
  <bar>this is a bar</bar>
</response>

هذا هو العقد والأنواع الداعمة كتبت

[ServiceContract]
[XmlSerializerFormat]
public interface IFooBarService
{
    [OperationContract]
    [WebGet(
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "foo?key={apikey}")]
    FooResponse GetFoo(string apikey);

    [OperationContract]
    [WebGet(
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "bar?key={apikey}")]
    BarResponse GetBar(string apikey);
}

[XmlRoot("response")]
public class FooResponse
{
    [XmlElement("foo")]
    public string Foo { get; set; }
}

[XmlRoot("response")]
public class BarResponse
{
    [XmlElement("bar")]
    public string Bar { get; set; }
}

ثم موكلي يبدو وكأنه هذا

static void Main(string[] args)
{
    using (WebChannelFactory<IFooBarService> cf = new WebChannelFactory<IFooBarService>("thirdparty"))
    {
        var channel = cf.CreateChannel();
        FooResponse result = channel.GetFoo("1234");
    }
}

عندما أقوم بتشغيل هذا أحصل على الاستثناء التالي

غير قادر على التحمل جسم XML مع اسم الجذر "استجابة" واسم مساحة الاسم "(لتشغيل" GetFoo "والعقد ('ifoobarservice'، 'http://tempuri.org/')) باستخدام xmlserializer. تأكد من إضافة النوع المقابل إلى XML إلى مجموعة الأنواع المعروفة للخدمة.

إذا أعلنت GetBar العملية من IFooBarService, ، أنه يعمل بشكل جيد. أعلم أنني أفتقد مفهوم مهم هنا - فقط لا أعرف ما الذي يجب البحث عنه. ما هي الطريقة الصحيحة لبناء أنواع العقد الخاصة بي، حتى يتمكنوا من التحمل بشكل صحيح؟

هل كانت مفيدة؟

المحلول

أود أن أقول خدمة طرفك الثالث مكسورة بشكل سيء. هناك تصادم مساحة الاسم هنا - هناك عنصران يدعى response ولكن مع أنواع مخطط XML مختلفة.

أعتقد أنك سوف تضطر إلى استخدام أي تقنية .NET تتضمن تحيزي هذا XML. لن تكون هناك طريقة لإخبارها .NET Type Type to Deserialize XML.

عليك فقط أن تفعل ذلك باليد. Linq إلى XML مفيد لهذا الغرض.

نصائح أخرى

يمكنك محاولة مع فئة الاستجابة مثل هذا:

[XmlRoot("response")]
public class Response
{
    [XmlElement("foo")]
    public string Foo { get; set; }

    [XmlElement("bar")]
    public string Bar { get; set; }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top