C# WebInvoke POST请求仅在手动写入url时有效
这是我的webget方法C# WebInvoke POST请求仅在手动写入url时有效,c#,wcf,xamarin.forms,dotnet-httpclient,C#,Wcf,Xamarin.forms,Dotnet Httpclient,这是我的webget方法 client.PostAsync("http://localhost:20968/Service1.svc/insert/x,y,z", "entry"); 给定OP中声明的uri模板,您构造的请求是错误的。已经指出,在手动构造uri时,它可以工作。发送请求时重复相同的构造 没有提供足够的关于目标web方法的详细信息,因此下面的示例假设使用 [WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapp
client.PostAsync("http://localhost:20968/Service1.svc/insert/x,y,z", "entry");
给定OP中声明的uri模板,您构造的请求是错误的。已经指出,在手动构造uri时,它可以工作。发送请求时重复相同的构造 没有提供足够的关于目标web方法的详细信息,因此下面的示例假设使用
[WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json,UriTemplate = "insert/{username}/{userpassword}/{usermobile}")]
通过手动构造请求,调用服务可能看起来像这样
[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);
}
公共异步任务插入(字符串x、字符串y、字符串z){
使用(var client=new HttpClient()){
client.BaseAddress=新Uri(“http://localhost:20968/Service1.svc/");
//UriTemplate=“插入/{username}/{userpassword}/{usermobile}”
var url=string.Format(“插入/{0}/{1}/{2}”,x,y,z);
System.Diagnostics.Debug.WriteLine(url);
var request=newhttprequestmessage(HttpMethod.Post,url);
系统.诊断.调试.写入线(请求);
var result=wait client.sendaync(请求);
返回wait result.Content.ReadAsStringAsync();
}
}
只有在我设置entry=“”、url如下“是的,但我不应该序列化对象并发送它们吗?使用JsonConvert.SerializeObject解决安全问题?如果我有很多参数要发送呢?假设我有一个包含多个联接的查询,谢谢
[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();
}
}