Windows Phone 8 调用 WCF web 服务
问题描述:
我的任务是编写需要链接到 WCF Web 服务的 WP8 应用程序,但我终生无法弄清楚自己做错了什么
I have been tasked with writing a WP8 application that needs to link to a WCF web service but I can't for the life of me figure out what I am doing wrong
我无法更改 WCF 服务,它不是我的
I can't change the WCF service, it's not mine
我正在努力使用的方法将一个类作为参数并返回一个不同的类作为结果
The method I am struggling with takes a class as a parameter and returns a different class as the result
我得到的一个测试方法的接口是:
The interface I have been given for a test method is:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "TestLogin")]
TestResults TestLogin(TestDetails Test);
public class TestDetails
{
public string Username { get; set; }
public string Password { get; set; }
public string DeviceId { get; set; }
}
public string TestResult
{
public int TestId { get; set; }
public List<TestOrders> Orders { get; set; }
}
我尝试过 RestSharp,但我收到了一个糟糕的请求
I have tried RestSharp but I just get a bad request
任何建议将不胜感激
这是我的示例代码:
var client = new RestClient
{
BaseUrl = "http://www.testing.co.uk/Services/Service.svc"
};
var dto = new TestDetails
{
username = "abc",
password = "123",
DeviceId = String.Empty,
DeviceModel = String.Empty
};
var request = new RestRequest
{
Resource = "Testlogin",
RequestFormat = DataFormat.Json,
Method = Method.POST
};
request.AddParameter("TestDetails", dto, ParameterType.RequestBody);
// request.AddBody(dto);
var response = client.Post<TestResult>(request);
答
OK 搞定了 :-) 我已经改用 HttpClient
OK figured it out :-) I've switched to using HttpClient
public static void Testing()
{
var c = new HttpClient
{
BaseAddress = new Uri("http://www.testing.co.uk/Services/Service.svc/")
};
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var json = "{\"login\":{\"DeviceId\":\"\",\"Password\":\"123\",\"Username\":\"abc\",\"DeviceModel\":\"\"}}";
var req = new HttpRequestMessage(HttpMethod.Post, "TestLogin")
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
c.SendAsync(req).ContinueWith(respTask =>
{
var response = respTask.Result.Content.ReadAsStringAsync();
Console.WriteLine("Response: {0}", respTask.Result);
});
}