2016-08-22 7 views
2

クライアントパート(Xamarin.Forms PCL)とWebサービスパート(WCF Rest)を含むVisual Studio(2015)プロジェクトがあります。 Webサービスはedmxを使用してデータベースと通信します(SQL Server 2016)。 JSONを使用してデータを交換します。不正なリクエスト - ポストメソッド - JSON DateTimeの問題

私はWCF Restサービスを新規作成または使用しています。 GETメソッドを使用しても問題はありませんが、POSTメソッドの問題があります。

このメソッドは、正常に機能するサービスの一部です.GETベースのメソッドでは問題ありません。 URLやクライアント(PCL Xamarin.Forms)からテストするとうまく動作します。

POSTメソッド(私の初めてのこと)はもう少し問題です。

SQL Server(2016)のテーブルに新しいレコードを作成することになっています。

私はPostman(https://www.getpostman.com/)を使用してテストすると、すでにテーブルにレコードが作成されていますが、オブジェクトには2つの日付があり、2つの日付は1970-01-01に置き換えられています。

クライアントを使用してWebサービスにアクセスすると、「Bad Request」が表示されます。

解決策を探して、Datetime値を代入するのではなく、1970年1月1日からのミリ秒数を配置するのが最適であることがわかりました。

私はこの忠告を郵便配達員に使用し、新しい回線の作成が正常に機能していることに気付きました。郵便配達依頼の

ボディ:今

{ 
"Reservation_Utilisateur_Id" : "4", 
"Reservation_Velo_Id" : "2", 
"Reservation_DateDebut" : "\/Date(1245398693390)\/", 
"Reservation_PeriodeDebut" : "matin", 
"Reservation_DateFin" :"\/Date(1245398693390)\/", 
"Reservation_PeriodeFin" : "matin" 
} 

、私は、サーバーに送信するために、そのオブジェクトを取得する方法を知っているように思います。上記のようにオブジェクトをどのように直列化できますか?

私は解決策を探していませんでした。

「BikeSharingService.Reservationタイプのオブジェクトをデシリアライズするときにエラーが発生しました。DateTime content '2016-08-22T00:00:00 + 02:00'が '/ Date('で始まり、終了しません')/'をJSONの必要に応じて使用します。

誰かが私が説明であり、おそらく動作するいくつかのコードであると初心者に教えてください。ここで

は私のコードです:

私の契約:

[OperationContract] 
    [WebInvoke(Method = "POST", UriTemplate = "create", 
     ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
    Reservation create(Reservation reservation); 

サービス方法:クライアント側で

public Reservation create(Reservation reservation) 
    { 
     using (MyEntities bse = new MyEntities()) 
     { 
       Reservation re = new Reservation 
       { 
        Reservation_Utilisateur_Id = reservation.Reservation_Utilisateur_Id, 
        Reservation_Velo_Id = reservation.Reservation_Velo_Id, 
        Reservation_DateDebut = reservation.Reservation_DateDebut, 
        Reservation_PeriodeDebut = reservation.Reservation_PeriodeDebut, 
        Reservation_DateFin = reservation.Reservation_DateFin, 
        Reservation_PeriodeFin = reservation.Reservation_PeriodeFin, 
        Reservation_DemandeRecupDomCli = reservation.Reservation_DemandeRecupDomCli 

       }; 
       bse.Reservations.Add(re); 
       bse.SaveChanges(); 
      return re; 
     } 
    } 

:次に

const string Url1 = "http://localhost:51843/ServiceReservation.svc/create"; 

    public async Task<Reservation> create(Reservation reservation) 
    { 
      string json = JsonConvert.SerializeObject(reservation); 
      var client = new HttpClient(); 
      client.DefaultRequestHeaders.Add("Accept", "application/json"); 
      var response = await client.PostAsync(Url1, 
          new StringContent(
           json, 
          Encoding.UTF8, "application/json")); 
          return JsonConvert.DeserializeObject<Reservation>(
      await response.Content.ReadAsStringAsync());    
    } 

メソッドを呼び出しますクライでNT側:私は何を得る

 Reservation re =new Reservation(); 
     re.Reservation_Utilisateur_Id = 4; 
     re.Reservation_Velo_Id = 2; 
     re.Reservation_DateDebut = DateTime.Now.Date; 
     re.Reservation_PeriodeDebut = "matin"; 
     re.Reservation_DateFin = DateTime.Now.Date; 
     re.Reservation_PeriodeFin = "matin"; 
     re.Reservation_DemandeRecupDomCli = 1; 

     Reservation resultat = await reManager.create(re); 

虚偽不正な要求メソッド:POST、RequestUri: 'http://localhost:51843/ServiceReservation.svc作成/'、バージョン:2.0、 内容:System.Net.Http.StringContent 、ヘッダ:{Accept: application/jsonコンテンツタイプ:application/json; charset = UTF-8
のContent-Length:407} BadRequest 1.1

タイプBikeSharingService.Reservationのオブジェクトをデシリアライズ中にエラーが発生しました。 DateTimeの内容 JSONの場合、 '/ Date('と ' ')の間に '2016-08-22T00:00:00 + 02:00'が開始されません。

+1

JSONは、標準の日付フォーマットを定義していませんが、それはJson.Net(.NETのウェブに面した部分で多く使用されていることは注目に値しますフレームワーク)は複数のフォーマットをサポートしています(そしてカスタムフォーマットもサポートしています)。したがって、すべてのクライアントで動作する規格を決定することができれば、Json(en/de)コーディングをネイティブに使用するよう設定できます。詳細はhttp://www.newtonsoft.com/json/help/html/datesinjson.htmを参照してください。 – Basic

+1

@Basicありがとうございました。私は、あなたが提案したページで提供された以下の情報を使用しました。そう単純な、実際JsonSerializerSettingsのmicrosoftDateFormatSettings :-) =新しいJsonSerializerSettings {DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }。 文字列microsoftJson = JsonConvert.SerializeObject(entry、microsoftDateFormatSettings); – user6742834

答えて

4

Jsonは標準の日付形式を定義していませんが、Json.Net(.NetフレームワークのほとんどのWeb対応部分で使用されています)が複数のforma箱から出して(そしてカスタムのものまで)。

すべてのクライアントで機能する標準を決定できる場合は、.NetのJson(en/de)コーディングをネイティブに使用するように設定できます。

日付形式ハンドラを指定する方法の詳細と詳細については、http://newtonsoft.com/json/help/html/datesinjson.htmを参照してください。

[リンクからサンプルコード]

public void WriteJsonDates() 
{ 
    LogEntry entry = new LogEntry 
    { 
     LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc), 
     Details = "Application started." 
    }; 

    // default as of Json.NET 4.5 
    string isoJson = JsonConvert.SerializeObject(entry); 
    // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"} 

    JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings 
    { 
     DateFormatHandling = DateFormatHandling.MicrosoftDateFormat 
    }; 
    string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings); 
    // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"} 

    string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter()); 
    // {"Details":"Application started.","LogDate":new Date(1234656000000)} 
} 
1

あなたが使用しようとしているのはEpoch DateTimeまたはUnix DateTimeです。

DateTimeオブジェクトをepoch datetimeに変換するには、ヘルパーメソッドを作成します。 1970年1月1日からミリ秒または秒のいずれかです。

また、必要に応じて変換するメソッドを持つ.NETの代わりにNoda DateTimeを使用することもできます。

DateTimeのデータ型がstringのNewクラスを作成し、キャストを指定することができます。または、カスタムSerializeメソッドで記述することもできます。

デフォルトでは、シリアル化後のDateTime形式はISO 8601 Formatになります。

UNIXやエポック日付時刻に変換するコード:

private static readonly DateTime EpochDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 

public static long ConvertDateTimeToUnixTime(DateTime date, bool isDatarequiredInMilliSeconds = false, DateTimeKind dateTimeKind = DateTimeKind.Local) 
{ 
    return Convert.ToInt64((DateTime.SpecifyKind(date.Value, dateTimeKind).ToUniversalTime() - EpochDateTime).TotalSeconds) * (isDatarequiredInMilliSeconds ? 1000 : 1); 
} 

あなたは(source)をバックに変換する必要がある場合には、以下を使用することができます。[コメントから昇格]

var milliseconds = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1'); 
var actualDate = new Date(parseInt(milliseconds)); 
+1

お返事ありがとうございました。私は実際にBasicによって提案されたJsonConverterを使用していました。とにかく、私の助けを求めてくれてありがとう。 – user6742834

関連する問題