【问题标题】:Windows Phone 8 call WCF web serviceWindows Phone 8 调用 WCF Web 服务
【发布时间】:2014-02-03 20:15:43
【问题描述】:

我的任务是编写一个需要链接到 WCF Web 服务的 WP8 应用程序,但我终其一生都无法弄清楚我做错了什么

我无法更改 WCF 服务,它不是我的

我正在努力的方法将一个类作为参数并返回一个不同的类作为结果

我得到的一个测试方法的接口是:

[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,但我收到了一个错误的请求

任何建议将不胜感激

这是我的示例代码:

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);

【问题讨论】:

  • 什么不起作用?你遇到了什么错误?
  • 我刚收到“错误请求”
  • 您能否使用 Fiddler 之类的工具来模拟请求,或者观察一个有效的请求,看看它与您发送的内容有何不同?
  • 我已经尝试过了,但我的请求无法正常工作,即使提琴手说请求不正确。我知道他们的 API 有效,因为他们的 Android 应用有效
  • 它是文档化的 API 吗?您可以从 API 的所有者那里获得帮助吗?

标签: c# wcf windows-phone-8 restsharp


【解决方案1】:

好的,想通了 :-) 我已经改用 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);
    });
}

【讨论】:

  • 如果我的方法名称为 GetOrder(string) 那么我应该写什么而不是 application/json 和“测试登录”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多