WebService没有反序列化一些对象

本文关键字:对象 反序列化 WebService | 更新日期: 2023-09-27 18:17:07

我做了一个Web服务(REST),我从Windows服务调用它。

有些电话似乎没有问题。而其他一些则返回了Bad Request。我将服务器设置为当反序列化数据为NULL时返回Bad Request。

Web Service已经使用EDMX从数据库生成了对象类。

本地服务有一个对Web服务的服务引用,所以它有相同的对象类可供使用。

我使用microsoft . asp.net . webapi . client Nuget Package从本地服务进行调用。

下面的代码WEB服务操作

//NOT WORKING
 [OperationContract]
 [WebInvoke(Method = "POST",
       UriTemplate = "{entity}/consent/{consent_id}/info")]
 bool ConsentInformation(string entity, string consent_id, consent info);
//WORKING
 [OperationContract]
 [WebInvoke(Method = "POST",
        UriTemplate = "{entity}/council/users")]
 void GoGetUsers(string entity, IEnumerable<council_user> user);

WEB服务代码

//NOT WORKING
 public void ConsentStatus(string entity, string consent_id, consent_status status)
        {            
            Utilities.SetResponseFormat();
            if (status == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;
                return;
            }
            gosubmitEntity entitys = new gosubmitEntity();
            consent_status consent = entitys.consent_status.FirstOrDefault(c => c.consent_id == consent_id && c.council_code == entity);
            if (consent == null)
                entitys.consent_status.Add(status);
            else
                consent = status;
            entitys.SaveChanges();
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Created;
        }
//WORKING
public void GoGetUsers(string entity, IEnumerable<council_user> users)
        {
            Utilities.SetResponseFormat();
            if (users == null || users.Count() == 0)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;
                return;
            }
            gosubmitEntity entitys = new gosubmitEntity();
            foreach (council_user user in users)
            {
                council_user dbUser = entitys.council_user.FirstOrDefault(u => u.username == user.username && u.council_code == entity);
                if (dbUser == null)
                    entitys.council_user.Add(user);                
                else
                    dbUser = user;
            }
            entitys.SaveChanges();
        }

本地业务代码

public static async Task<bool> POST<T>(string requestURI, T data)
        {
            HttpClient client = CreateClient();
            HttpResponseMessage response = await client.PostAsJsonAsync(requestURI, data);
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                DiagnosticLog.Write(99, $"Status response from webservice = {response.StatusCode}", string.Empty);
                return false;
            }
        }
 private static HttpClient CreateClient()
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri(Settings.BaseWebservice);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }

非工作对象类

public partial class consent_status
{
    public string consent_id { get; set; }
    public string council_code { get; set; }
    public string lodged { get; set; }
    public string processing { get; set; }
    public string rfis { get; set; }
    public string issued { get; set; }
    public string inspections { get; set; }
    public string ccc { get; set; }
    public Nullable<System.DateTime> date_lodged { get; set; }
    public Nullable<System.DateTime> date_granted { get; set; }
    public Nullable<System.DateTime> date_issued { get; set; }
    public Nullable<System.DateTime> date_cccissued { get; set; }
    public Nullable<int> days_live { get; set; }
    public Nullable<int> days_inactive { get; set; }
    public Nullable<int> days_suspended { get; set; }
    public Nullable<System.DateTime> form6_received { get; set; }
    public string ccc_file_name { get; set; }
    public Nullable<System.DateTime> last_updated { get; set; }
}

POST数据示例

{"ccc":"","ccc_file_name":"","consent_id":"120266","council_code":"DEMO","date_cccissued":null,"date_granted":null,"date_issued":null,"date_lodged":"2012-05-03T00:00:00","days_inactive":null,"days_live":null,"days_suspended":null,"form6_received":null,"inspections":"In Progress","issued":"","last_updated":null,"lodged":"Accepted","processing":"","rfis":"Pending"}

任何想法都将非常感激。

谢谢

WebService没有反序列化一些对象

您的问题是您正在使用的两种技术,WCF Rest和HttpClient.PostAsJsonAsync(),使用不同的序列化器。WCF Rest使用DataContractJsonSerializer,而PostAsJsonAsync内部使用使用Json的JsonMediaTypeFormatter

而且,不幸的是,这两个序列化器对日期有不同的默认格式(请记住,JSON中没有日期的标准表示):

  • 在Json。. NET中,您的日期被序列化为ISO 8601标准字符串"date_lodged": "2012-05-03T00:00:00"
  • 对于数据契约序列化器,它使用特殊的Microsoft格式"date_lodged":"'/Date(1336017600000-0400)'/"

因此,当WCF rest服务内部使用的DataContractJsonSerializer试图反序列化日期时,它会失败并抛出异常。

您有几个选项来解决这个问题。

首先,您可以配置WCF rest以使用不同的序列化器。这涉及到,参见WCF可扩展性-消息格式化器和WCF"原始"编程模型(Web)。

其次,您可以使用数据契约序列化器使您的客户端序列化。这很简单,只需设置JsonMediaTypeFormatter.UseDataContractJsonSerializer = true。我相信下面的扩展可以完成这项工作:

public static class HttpClientExtensions
{
    public static Task<HttpResponseMessage> PostAsDataContractJsonAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsJsonAsync(requestUri, value, CancellationToken.None);
    }
    public static Task<HttpResponseMessage> PostAsDataContractJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)
    {
        return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter { UseDataContractJsonSerializer = true }, cancellationToken);
    }
}

或者你可以坚持使用Json。并将默认日期格式更改为Microsoft格式:

public static class HttpClientExtensions
{
    public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, JsonSerializerSettings settings)
    {
        return client.PostAsJsonAsync(requestUri, value, settings, CancellationToken.None);
    }
    public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, JsonSerializerSettings settings, CancellationToken cancellationToken)
    {
        return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter { SerializerSettings = settings }, cancellationToken);
    }
}

使用

设置
        settings =  new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };

或者,你可以修改你的客户端,按照。net使用REST服务和解析REST服务JSON响应(c#)的方式来使用REST服务。

最后,您还可以考虑切换到ASP。. NET Web API,使用Json。