使用HttpWebRequest格式化POST数据

Vil*_*ger 1 c# silverlight wcf post httpwebrequest

我有一个包含两个操作的Web服务.一个操作使用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);
}
Run Code Online (Sandbox Code Playgroud)

我的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);
Run Code Online (Sandbox Code Playgroud)

我的网址正在正确生成.但是,只有GetProperty请求有效.当我在浏览器中复制并粘贴GetProperty网址时,它可以正常工作.当我尝试执行SetProperty时,我收到一个失败,说没有找到Endpoint.我知道浏览器总是使用GET,所以这是有道理的.但是,从HttpWebRequest,我得到一个错误,上面写着"远程服务器返回错误:NotFound".我究竟做错了什么?

谢谢!

mth*_*rba 5

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

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