WebInvoke POST请求仅在我手动编写URL时才有效

时间:2017-06-01 13:39:24

标签: c# wcf xamarin.forms dotnet-httpclient

public async Task<string> insert(string x, string y, string z)
{
    using (var client = new HttpClient())
    {         
        var payload = new rootnode { username = x, userpassword = y, usermobile = z };
        var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
        var entry = new StringContent(stringPayload, Encoding.UTF8, "application/json");

        System.Diagnostics.Debug.WriteLine(entry);
        var result = await client.PostAsync("http://localhost:20968/Service1.svc/insert/", entry);
        return await result.Content.ReadAsStringAsync();               
    }
}

只有当我使用entry =&#34;&#34;

手动编写网址时,我的功能才能正常运行
client.PostAsync("http://localhost:20968/Service1.svc/insert/x,y,z", "entry");

这是我的webget方法

[WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json,UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]

1 个答案:

答案 0 :(得分:0)

鉴于OP中声明的uri模板,您正在构建错误的请求。已经表明,当人工构建uri时它起作用了。发送请求时重复相同的构造。

没有提供有关目标Web方法的详细信息,因此以下示例假定使用类似...

的内容
[ServiceContract]
public interface IService {
    [OperationContract]
    [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped, 
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]
    InsertResponse Insert(string username, string userpassword, string usermobile);
}

通过手动构建请求,调用服务可能如下所示

public async Task<string> insert(string x, string y, string z) {
    using (var client = new HttpClient()) {
        client.BaseAddress = new Uri("http://localhost:20968/Service1.svc/");

        //UriTemplate = "insert/{username}/{userpassword}/{usermobile}"
        var url = string.Format("insert/{0}/{1}/{2}", x, y, z);
        System.Diagnostics.Debug.WriteLine(url);

        var request = new HttpRequestMessage(HttpMethod.Post, url);
        System.Diagnostics.Debug.WriteLine(request);

        var result = await client.SendAsync(request);
        return await result.Content.ReadAsStringAsync();
    }
}