繁体   English   中英

C#WPF服务自定义请求格式

[英]C# WPF Service custom request format

我有一个WCF Serivce,它读取带有XML有效负载的请求并响应这些请求。 例如,一个简单的登录请求如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LoginRequest>
    <username>test</username>
    <password>foo</password>
</LoginRequest>

现在我知道我可以在服务方法中简单地接受XElement ,但是有什么方法可以告诉底层系统如何读取上述XML并将其转换为以下格式的函数调用:

public LoginResponse Login (string username, string password); 

这样的事情可能吗?

我不认为您指定的XML可以按实际格式格式化。 我只说这是因为,除非您更改传入的SOAP消息,否则它将内部的XML识别为单个字符串值(就像您现在看到的那样),而不是多个值。

如果您有.NET客户端,那么您将希望在客户端(或代理对象)上利用已经用DataContract属性修饰的相同类,这些类已经知道如何序列化和反序列化为SOAP格式。 由于您没有指定向您发送XML有效负载的客户端,因此很有可能XML已经包装在SOAP信封中,并且需要对双方进行一些大修才能“更正确”。

此外,由于要执行的操作,实际的SOAP请求必须进行重大更改才能将其作为参数传递,而不仅仅是XML值。

因此,我想最基本的答案是“否”。 您将无法单独更改WCF服务来执行此操作。

是的 ,有可能。

a)将xml更改为

<Login>
     <username>test</username>
     <password>foo</password>
</Login>

b)[ServiceContract] [ServiceContract(Namespace = "")]替换[ServiceContract] [ServiceContract(Namespace = "")]

c)和声明方法为

[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Xml, 
           ResponseFormat = WebMessageFormat.Xml, 
           BodyStyle = WebMessageBodyStyle.Wrapped)]
public string Login(string username, string password){}

它有效...

这是我用来测试的代码

public void TestWCFService()
{
    //Start Server
    Task.Factory.StartNew(
        (_) =>
        {
            Uri baseAddress = new Uri("http://localhost:8080/Test");
            WebServiceHost host = new WebServiceHost(typeof(TestService), 
                                                     baseAddress);
            host.Open();
        }, null, TaskCreationOptions.LongRunning).Wait();


    //Client
    string xml = @"<Login>
                      <username>test</username>
                      <password>foo</password>
                  </Login>";

    var wc = new WebClient();
    wc.Headers.Add("Content-Type", "application/xml; charset=utf-8");
    var result = wc.UploadString("http://localhost:8080/Test/Login", xml);
}

[ServiceContract(Namespace = "")]
public class TestService
{
    [OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Xml, 
               ResponseFormat = WebMessageFormat.Xml, 
               BodyStyle = WebMessageBodyStyle.Wrapped)]
    public string Login(string username, string password)
    {
        return username + " " + password;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM