1

我有一个尝试访问 RESTful WCF 服务的 Windows 8 应用程序。

我还尝试使用控制台应用程序访问该服务,但出现相同错误。

我有一个基本对象,我正试图从我的 Win8 客户端发送到服务,但我收到 HTTP 400 错误。

服务代码

[DataContract(Namespace="")]
public class PushClientData
{
    [DataMember(Order=0)]
    public string ClientId { get; set; }

    [DataMember(Order=1)]
    public string ChannelUri { get; set; }
}

[ServiceContract]
public interface IRecruitService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "client")]
    void RegisterApp(PushClientData app);
}

public class RecruitService : IRecruitService
{
    public void RegisterApp(PushClientData app)
    {
        throw new NotImplementedException();
    }
}

客户端代码

protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        var data = new PushClientData
                       {
                           ClientId = "client1",
                           ChannelUri = "channel uri goes here"
                       };
        await PostToServiceAsync<PushClientData>(data, "client");
    }

    private async Task PostToServiceAsync<T>(PushClientData data, string uri)
    {
        var client = new HttpClient { BaseAddress = new Uri("http://localhost:17641/RecruitService.svc/") };

        StringContent content;
        using(var ms = new MemoryStream())
        {
            var ser = new DataContractSerializer(typeof (T));
            ser.WriteObject(ms, data);
            ms.Position = 0;
            content = new StringContent(new StreamReader(ms).ReadToEnd());
        }

        content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
        var response = await client.PostAsync(uri, content);

        response.EnsureSuccessStatusCode();
    }

我究竟做错了什么?

我已经查看了提琴手中的请求,它会发出

http://localhost:17641/RecruitService.svc/client

就像我认为应该的那样,但每次返回都是错误 400(错误请求)。

编辑

Fiddler 的原始请求如下。我添加了 . 在 localhost 之后,Fiddler 会接它。如果我接受或留下它,我会得到同样的错误。

POST http://localhost.:17641/RecruitService.svc/clients HTTP/1.1
Content-Type: text/xml
Host: localhost.:17641
Content-Length: 159
Expect: 100-continue
Connection: Keep-Alive

<PushClientData xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ClientId>client1</ClientId>
    <ChannelUri>channel uri goes here</ChannelUri>
</PushClientData>
4

1 回答 1

-1

嗨@Michael在这里你错过了ServiceContract中的一些东西

代替

 [WebInvoke(UriTemplate = "client")]
 void RegisterApp(PushClientData app);

用。。。来代替

 [WebInvoke(UriTemplate = "client")]
 void client(PushClientData app);

或使其成为

 [WebInvoke(UriTemplate = "RegisterApp")]
 void RegisterApp(PushClientData app);

UriTemplate 值必须与 ServiceContract 方法名称相同。

于 2012-10-19T12:39:11.803 回答