【问题标题】:WCF REST Service: Method parameter (object) is nullWCF REST 服务:方法参数(对象)为空
【发布时间】:2013-04-03 11:44:59
【问题描述】:

为什么我的 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) Bad Request。

有什么帮助吗?谢谢

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

【问题讨论】:

    标签: wcf rest webclient


    【解决方案1】:

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

    找出要发送到 WCF REST 服务的内容的一种方法是使用 WCF 客户端本身 - 使用 WebChannelFactory&lt;T&gt; 类,然后使用诸如 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);
        }
    }
    

    【讨论】:

    • 我曾使用“bare”作为正文样式,但后来我得到“远程服务器返回错误:(400) 错误请求。”错误
    【解决方案2】:

    已解决,谢谢

    我把 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。

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 1970-01-01
      • 2016-08-13
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多