首页 新闻 会员 周边

WCF REST POST数据问题

0
悬赏园豆:30 [已解决问题] 解决于 2015-11-24 16:01

Contract [类库]
[ServiceContract(Namespace="www.baidu.com")]
public interface IEmployees
{
[WebGet(UriTemplate = "{id}")]
[OperationContract]
Employee Get(string id);

[WebInvoke(UriTemplate = "/Create", Method = "POST",RequestFormat = WebMessageFormat.Xml,ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
string Create(Employee employee);

}
[DataContract]
public class Employee
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
}

Service:[类库]
public class EmployeesService : IEmployees
{
public string Create(Employee employee)
{ return "XX"; }

public Employee Get(string id)
{return new Employee(){Id="1",Name="Brad"}; }
}

Hosting :[控制台程序]
config
<configuration>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="Service.EmployeesService">
<endpoint address="http://127.0.0.1:8088/employees" 
binding="webHttpBinding"
behaviorConfiguration="webHttp"
contract="Interface.IEmployees"/>
</service>
</services>
</system.serviceModel>
</configuration>

Main()
{
using (WebServiceHost host = new WebServiceHost(typeof(EmployeesService)))
{
host.Opened+=delegate{ Console.WriteLine("Running..."); };
host.Open();
Console.Read();
}
}

Client:[控制台程序]
Main()
{
string msg="<employee xmlns:a=\"http://www.artech.com/\""
+" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"
+"<Id>003</Id><Name>王五</Name></Employee>"
byte[] data = Encoding.UTF8.GetBytes(msg);
string url ="http://127.0.0.1:8088/employees/Create"
WebClient client = new WebClient(); 
client.Headers.Add("Content-Type", "application/xml");
byte[] responseData = client.UploadData(url, "POST", data); //这行直接报错
Console.WriteLine(Encoding.UTF8.GetString(responseData));
}

错误信息:
WebException was unhandled
an unhandled exception of type 'System.Net.WebException ' occurred in System.dll
Addition infomation: 在webClient请求期间发生异常


GET请求正确,POST请求错误。谢谢

问题补充:


System.Net.WebException:远程服务器返回错误:<400> 错误的请求
在System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data,WebRequest& ewquest)
在System.Net.WebClient.UploadData(Uri address, String method, Byte[] data)
在System.Net.WebClient.UploadDataInternal(String address, String method, Byte[] data)
在 <类库名称>.Post()位置 <Client工程文件位置> :行号 45

TFS的主页 TFS | 初学一级 | 园豆:89
提问于:2015-08-05 13:25
< >
分享
最佳答案
0

改用HttpWebRquest,成功

TFS | 初学一级 |园豆:89 | 2015-08-05 16:20
其他回答(1)
0

异常不止这些吧,你把详细信息贴出来

 

client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("ContentLength", data.Length.ToString());

 

收获园豆:30
MrNice | 园豆:3450 (老鸟四级) | 2015-08-05 13:45

"application/x-www-form-urlencoded" 类型会追加body进去,服务端是无法获取数据

支持(0) 反对(0) TFS | 园豆:89 (初学一级) | 2015-08-05 16:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册