来自Win8应用程序的HttpClient.PostAsync到WCF服务给出错误400错误请求

时间:2012-08-30 23:31:15

标签: .net wcf rest windows-8

我有一个试图访问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>

1 个答案:

答案 0 :(得分:-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方法名称相同。

相关问题