Skip to main content
 首页 » 编程设计

c#之使用 HttpWebRequest 格式化为 POST 数据

2024年02月03日27lori

我有一个包含两个操作的网络服务。一个操作使用 GET,另一个使用 POST。请注意,我不是网络服务专家,所以请随时指出我做错的任何事情。无论如何,我的 WCF 服务中有以下操作:

[WebGet(UriTemplate = "/GetPropertyValue/{propertyID}", ResponseFormat = WebMessageFormat.Json)] 
public string GetPropertyValue(string propertyID) 
{ 
  return RetrievePropertyValueFromDatabase(propertyID); 
} 
 
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
public string SetPropertyValue(string propertyID, string propertyValue) 
{ 
  return SetPropertyValueInDatabase(propertyID, propertyValue); 
} 

我的 Silverlight Phone 应用程序正在调用这两个操作。出于性能原因,此调用必须使用 HttpWebRequest。为了打这个电话,我正在做的是:

// Getting Property Value 
string url = GetUrl(propertyID); 
// url looks something like http://mydomain.com/myservice.svc/GetPropertyValue/2 
WebRequest request = HttpWebRequest.Create(url); 
request.BeginGetResponse(new AsyncCallback(GetProperty_Completed), request); 
 
// Elsewhere in my code 
 
// Setting property value 
string url = GetUrl(propertyID, propertyValue); 
// url looks something like http://mydomain.com/myservice.svc/SetPropertyValue/2/newValue 
WebRequest request = HttpWebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
request.BeginGetResponse(new AsyncCallback(SetProperty_Completed), request); 

我的网址正在正确生成。但是,只有 GetProperty 请求有效。当我在浏览器中复制并粘贴 GetProperty url 时,它起作用了。当我尝试执行 SetProperty 时,我收到一条失败消息,提示未找到端点。我知道浏览器总是使用 GET,所以这是有道理的。但是,从 HttpWebRequest 中,我收到一条错误消息,指出“远程服务器返回错误:NotFound”。我做错了什么?

谢谢!

请您参考如下方法:

您忘记在 [WebInvoke] 属性中声明 UriTemplate。根据代码片段中的示例 URL,它必须是 "SetPropertyValue/{propertyID}/{propertyValue}"。这就是它返回 404 的原因。

此外,您当然不想使用“application/x-www-form-urlencoded”作为请求内容类型。 WCF 没有那个 MessageFormatter。另外,您甚至不会为此请求发送任何内容(WCF 将使用 UriTemplateDispatchFormatter)。因此,您还可以远程访问 RequestFormat 和 BodyStyle 属性。仅当您真的希望 Json 回来时才将 ResponseFormat 属性保留在那里!