WCF REST服务:方法参数(对象)为空

时间:2013-04-03 11:45:00

标签: wcf rest webclient

为什么我的WCF Rest服务方法的参数总是为空?....我确实访问了服务的方法,我确实得到了wcf方法返回的字符串,但参数仍为null。

运营合同:

  [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配置中的服务地址如下:

<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; }
    }

2 个答案:

答案 0 :(得分:4)

你似乎走在正确的轨道上。您需要Bare正文样式,否则您需要将输入的序列化版本包装在另一个JSON对象中。第二个代码应该可行 - 但是如果没有关于如何设置服务以及GetURL()返回的更多信息,我们只能猜测。

找出要发送到WCF REST服务的内容的一种方法是使用WCF客户端本身 - 使用WebChannelFactory<T>类,然后使用Fiddler等工具查看它发送的内容。以下示例为SSCCE,可显示您的方案正常运行。

public class StackOverflow_15786448
{
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "AddNewLocation",
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        string AddNewLocation(NearByAttractions newLocation);
    }
    public class NearByAttractions
    {
        public double Lat { get; set; }
        public double Lng { get; set; }
        public string Name { get; set; }
    }
    public class Service : ITest
    {
        public string AddNewLocation(NearByAttractions newLocation)
        {
            if (newLocation == null)
            {
                //I'm always getting this text in my logfile
                Console.WriteLine("In add new location:- Is Null");
            }
            else
            {
                Console.WriteLine("In add new location:- ");
            }

            //String is returned even though parameter is null
            return "59";
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        Console.WriteLine("Using WCF-based client (WebChannelFactory)");
        var factory = new WebChannelFactory<ITest>(new Uri(baseAddress));
        var proxy = factory.CreateChannel();
        var newLocation = new NearByAttractions { Lat = 12, Lng = -34, Name = "56" };
        Console.WriteLine(proxy.AddNewLocation(newLocation));

        Console.WriteLine();
        Console.WriteLine("Now with WebClient");

        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(baseAddress + "/AddNewLocation", json);

        Console.WriteLine(r);
    }
}

答案 1 :(得分:3)

解决了,谢谢

我将BodyStyle更改为“Bare”所以我的服务界面如下:

  [OperationContract]
    [WebInvoke(UriTemplate = "AddNewLocation",
        Method="POST",
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    string AddNewLocation(NearByAttractions newLocation);

然后按如下方式实现我的客户端:

MemoryStream ms = new MemoryStream();

        DataContractJsonSerializer serialToUpload = new DataContractJsonSerializer(typeof(NearByAttractions));
        serialToUpload.WriteObject(ms, newLocation);


        WebClient client = new WebClient();
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

        client.UploadData(GetURL() + "AddNewLocation", "POST", ms.ToArray());

我使用了WebClient.UploadData而不是UploadString。