#c# #rest #wcf
#c# #rest #wcf
Вопрос:
Я создал службу WCF на C #. Мне нужно принять POST-запрос с телом XML и десериализовать XML.
[DataContract(Name = "EmployeeInformation", Namespace = "urn:test")]
public class EmployeeInformation1
{
[DataMember(Name = "Employee")]
public Employee Employee { get; set; }
}
[DataContract(Name = "Employee", Namespace = "urn:test")]
[KnownType(typeof(Common))]
public class Employee
{
[DataMember(Name = "ID")]
public string ID { get; set; }
[DataMember(Name = "Common")]
public Common Common { get; set; }
}
[DataContract(Name = "Common", Namespace = "urn:test")]
public class Common
{
[DataMember(Name = "ID")]
public string ID { get; set; }
}
//-----------------------------------------------------
[ServiceContract]
public interface IService1
{
[OperationContract]
[ServiceKnownType(typeof(Common))]
[WebInvoke(Method = "POST", UriTemplate = "/test",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare)]
string Test(EmployeeInformation1 xmlstring);
}
Служба получает и десериализует корневые атрибуты объекта должным образом. Однако все атрибуты из Common равны нулю.
XML
<?xml version="1.0" encoding="utf-8"?>
<EmployeeInformation xmlns="urn:test">
<Employee>
<ID>ID1</ID>
<Common>
<ID2>ID2</ID2>
</Common>
</Employee>
</EmployeeInformation>
Комментарии:
1. После моего теста я обнаружил, что у вашего сервиса нет проблем. Я использовал Postman для отправки данных. Служба может нормально получать данные, и они не пустые. Как вы отправляете данные? Я думаю, что это может быть проблемой на стороне клиента.
2. Спасибо! Я тоже использую Postman. Может быть, функция тестирования неверна?
3. проверка общедоступной строки(EmployeeInformation1 xmlstring) { string param2 = xmlstring. Сотрудник. Обычный. ID; возвращает param2; }
4. Почтальон не получил данные?
5. Какой у вас файл конфигурации?
Ответ №1:
Вот моя демонстрация:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApp84
{
[DataContract(Name = "EmployeeInformation", Namespace = "urn:test")]
public class EmployeeInformation1
{
[DataMember(Name = "Employee")]
public Employee Employee { get; set; }
}
[DataContract(Name = "Employee", Namespace = "urn:test")]
[KnownType(typeof(Common))]
public class Employee
{
[DataMember(Name = "ID")]
public string ID { get; set; }
[DataMember(Name = "Common")]
public Common Common { get; set; }
}
[DataContract(Name = "Common", Namespace = "urn:test")]
public class Common
{
[DataMember(Name = "ID")]
public string ID { get; set; }
}
//-----------------------------------------------------
[ServiceContract]
public interface IService1
{
[OperationContract]
[ServiceKnownType(typeof(Common))]
[WebInvoke(Method = "POST", UriTemplate = "/test",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare)]
string Test(EmployeeInformation1 xmlstring);
}
public class Service1 : IService1
{
public string Test(EmployeeInformation1 xmlstring)
{
Console.WriteLine(xmlstring.Employee.Common.ID);
return xmlstring.Employee.Common.ID;
}
}
class Program
{
static void Main(string[] args)
{
ServiceHost selfHost = new ServiceHost(typeof(Service1));
selfHost.Open();
Console.WriteLine("Service open");
Console.ReadKey();
selfHost.Close();
}
}
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.serviceModel>
<services>
<service name="ConsoleApp84.Service1" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8012/ServiceModelSamples/service"/>
</baseAddresses>
</host>
<endpoint address=""
binding="webHttpBinding"
contract="ConsoleApp84.IService1"
behaviorConfiguration="ESEndPointBehavior" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ESEndPointBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Комментарии:
1. Спасибо! Моя проблема заключалась в неправильном XML. <Общий> должен быть выше <ID>