简体   繁体   English

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

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

I have added a rest API to a WCF service, unfortunately I don't really understand how to handle the POST calls correctly.我已经向 WCF 服务添加了一个 rest API,不幸的是我并不真正了解如何正确处理 POST 调用。 For example, at WCF Service is this Save Fuction:例如,在 WCF 服务中是这个保存函数:

Interface VB.Net:接口 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

Function VB.Net:函数 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 .......

Now I try to call this function in my application via the API:现在我尝试通过 API 在我的应用程序中调用此函数:

C#: 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;
        }
    }

Now the function is called via the API but the object is not passed to the function and is still null.现在通过 API 调用函数,但对象没有传递给函数并且仍然为空。 What am I doing wrong here?我在这里做错了什么?

Let me know if this is something that helps you:让我知道这是否对您有帮助:

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

    }

In the end it was an problem with the DateTime propertys, now I handle it this way:最后这是 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;
    }

}

Maybe it helps someone else.也许它可以帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM