为什么我的 WCF Rest 服务方法的参数始终为空?....我确实访问了服务的方法,并且确实获得了 wcf 方法返回的字符串,但参数仍然为空。
运营合同:
[OperationContract]
[WebInvoke(UriTemplate = "AddNewLocation",
Method="POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
string AddNewLocation(NearByAttractions newLocation);
AddNewLocation 方法的实现
public string AddNewLocation(NearByAttractions newLocation)
{
if (newLocation == null)
{
//I'm always getting this text in my logfile
Log.Write("In add new location:- Is Null");
}
else
{
Log.Write("In add new location:- " );
}
//String is returned even though parameter is null
return "59";
}
客户端代码:
WebClient clientNewLocation = new WebClient();
clientNewLocation.Headers[HttpRequestHeader.ContentType] = "application/json";
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue;
//Serialising location object to JSON
string serialLocation = js.Serialize(newLocation);
//uploading JSOn string and retrieve location's ID
string jsonLocationID = clientNewLocation.UploadString(GetURL() + "AddNewLocation", serialLocation);
我也在我的客户端尝试了这段代码,但仍然得到一个空参数
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(NearByAttractions));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, newLocation);
String json = Encoding.UTF8.GetString(ms.ToArray());
WebClient clientNewLocation = new WebClient();
clientNewLocation.Headers[HttpRequestHeader.ContentType] = "application/json";
string r = clientNewLocation.UploadString(GetURL() + "AddNewLocation", json);
Console.Write(r);
然后我还将BodyStyle选项更改为“ Bare ”,但随后出现以下错误(使用两个客户端代码):
远程服务器返回错误:(400) 错误请求。
请问有什么帮助吗?谢谢
编辑 1: 我的 GetUrl() 方法从 Web 配置文件加载 Web 服务 IP 地址并返回 Uri 类型的对象
private static Uri GetURL()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/web.config");
string sURL = config.AppSettings.Settings["serviceURL"].Value;
Uri url = null;
try
{
url = new Uri(sURL);
}
catch (UriFormatException ufe)
{
Log.Write(ufe.Message);
}
catch (ArgumentNullException ane)
{
Log.Write(ane.Message);
}
catch (Exception ex)
{
Log.Write(ex.Message);
}
return url;
}
web config中存储的服务地址如下:
<appSettings>
<add key="serviceURL" value="http://192.168.2.123:55666/TTWebService.svc/"/>
</appSettings>
这就是我的 NearByAttraction 类的定义
[DataContractAttribute]
public class NearByAttractions
{
[DataMemberAttribute(Name = "ID")]
private int _ID;
public int ID
{
get { return _ID; }
set { _ID = value; }
}
[DataMemberAttribute(Name = "Latitude")]
private string _Latitude;
public string Latitude
{
get { return _Latitude; }
set { _Latitude = value; }
}
[DataMemberAttribute(Name = "Longitude")]
private string _Longitude;
public string Longitude
{
get { return _Longitude; }
set { _Longitude = value; }
}