如何使用 post 从 WCF 服务调用方法并将对象传递给它?

How do you use post to call a method from a WCF service and pass it an object?

我已经向 WCF 服务添加了休息 API,不幸的是我真的不明白如何正确处理 POST 调用。例如,在 WCF 服务中是这个 Save Fuction:

接口VB.Net:

      <OperationContract()>
<WebInvoke(Method:="POST", UriTemplate:="/saveNewAZEntry", BodyStyle:=WebMessageBodyStyle.Wrapped, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function SaveNewAZEntry(ByVal NewAZEntry As AZEntry) As AZEntry

函数VB.Net:

    Public Function SaveNewAZEntry(ByVal NewAZEntry As AZEntry) As AZEntry Implements IPMProService.SaveNewAZEntry

    If NewAZEntry.start.Date = NewAZEntry.finished.Date And DateDiff(DateInterval.Minute, NewAZEntry.start, NewAZEntry.finished) >= My.Settings.MinAZDauer Then .......

现在我尝试通过 API:

在我的应用程序中调用这个函数

C#:

    private static HttpClient _client = new HttpClient();
    private static string ServiceUrl = "http://localhost:64917/PMProService.svc/api";
    
    [HttpPost]
    internal static void SaveAZEntry(AZEntry azEntry)
    {
        var uri = new Uri($"{ServiceUrl}/saveNewAZEntry");

        try
        {
            var jsonString = JsonConvert.SerializeObject(azEntry);
            HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            HttpResponseMessage response = _client.PostAsync(uri, content).Result;
            response.EnsureSuccessStatusCode();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

现在通过 API 调用函数,但对象未传递给函数且仍为空。我在这里做错了什么?

如果这对您有帮助,请告诉我:

    public void SendDataToWCF(AZEntry aZEntry)
    {

        var uri = new Uri("http://localhost:64917/PMProService.svc/api/saveNewAZEntry");

        string strParam = string.Concat("param1=", aZEntry.param1, "&param2=", aZEntry.param2);
        byte[] data = Encoding.ASCII.GetBytes(strParam);

        // Create request
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);

        webrequest.Method = "POST";
        webrequest.ContentType = "application/x-www-form-urlencoded";
        webrequest.ContentLength = data.Length;

        //Send/Write data to your Stream/server
        using (Stream newStream = webrequest.GetRequestStream())
        {
            newStream.Write(data, 0, data.Length);
        }


        // get the response
        using (WebResponse resp = webrequest.GetResponse())
        {
            using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
            {
                var resultS = reader.ReadToEnd();
                // Do something with your response
            }
        }

    }

最后是DateTime属性的问题,现在我是这样处理的:

     internal static void SaveAZEntry(AZEntry azEntry)
    {
        var uri = new Uri($"{ServiceUrl}/saveNewAZEntry");

        try
        {
            _client.SendAsync(PostRequestMessage(azEntry, uri));
        }
        catch (Exception ex)
        {
            throw ex;
        }
       
    }
    
     private static HttpRequestMessage PostRequestMessage(object obj, Uri uri)
    {
        var options = new JsonSerializerOptions() { WriteIndented = true };
        options.Converters.Add(new CustomDateTimeConverter("dd/M/yyyy hh:mm:ss"));
        var jsonString = System.Text.Json.JsonSerializer.Serialize(obj, options);
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
        request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
        return request;
    }

     public class CustomDateTimeConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
{
    private readonly string Format;
    public CustomDateTimeConverter(string format) { Format = format; }
    public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
    {
        //date.Subtract(new DateTime(1970, 1, 1)).TotalSeconds
        //writer.WriteStringValue(date.ToString(Format));
        writer.WriteStringValue("/Date(" + ConvertDatetimeToUnixTimeStamp(date) + ")/");
        //writer.WriteStringValue(CreatedotNetDateFormat(date));
    }
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.ParseExact(reader.GetString(), Format, null);
    }

    public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
    {
        // Unix timestamp is seconds past epoch
        System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
        return dtDateTime;
    }
    public static long ConvertDatetimeToUnixTimeStamp(DateTime date)
    {
        date = date.ToLocalTime();
        var dateTimeOffset = new DateTimeOffset(date);
        var unixDateTime = dateTimeOffset.ToUnixTimeMilliseconds();
        return unixDateTime;
    }

}

也许对其他人有帮助。