3

为什么我的 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; }
    }
4

2 回答 2

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);
    }
}
于 2013-04-03T16:17:35.130 回答
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。

于 2013-04-04T12:26:41.980 回答