[英]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.