【问题标题】:WebInvoke POST request only works if I write the url manuallyWebInvoke POST 请求仅在我手动编写 url 时才有效
【发布时间】:2017-06-01 13:39:24
【问题描述】:
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=""

手动编写 url 时,我的功能才能很好地工作
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}")]

【问题讨论】:

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


【解决方案1】:

鉴于 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();
    }
}

【讨论】:

  • 是的,但我不应该序列化对象并发送它们吗?使用 JsonConvert.SerializeObject 解决安全问题?如果我有很多参数要发送怎么办?假​​设我有一个包含多个连接的查询,谢谢
猜你喜欢
  • 2019-11-23
  • 2014-03-10
  • 2012-05-26
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多