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
改用HttpWebRquest,成功
异常不止这些吧,你把详细信息贴出来
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("ContentLength", data.Length.ToString());
"application/x-www-form-urlencoded" 类型会追加body进去,服务端是无法获取数据