簡體   English   中英

WCF REST服務:方法參數(對象)為空

[英]WCF REST Service: Method parameter (object) is null

為什么我的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);

我也在我的客戶端嘗試了這個代碼,但仍然得到一個null參數

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

你似乎走在正確的軌道上。 您需要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);
    }
}

解決了,謝謝你

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM