2

I am using a mono self hosted servicestack application with the ServiceStack.Razor rendering. In the application the user enters into a form a UK date (dd/mm/yyyy) but this is converted to a US date (mm/dd/yyyy) on a HTTP POST.

In a normal MVC application I would do this using model binding as shown here ASP.NET MVC3: Force controller to use date format dd/mm/yyyy

How do you do this in ServiceStack as I could not find anything about it.

4

1 回答 1

3

您可以使用自定义序列化器/反序列化器来全局控制 DateTime 值的序列化和反序列化:

在您的 AppHost 中:

using ServiceStack.Text;

JsConfig<DateTime>.SerializeFn = SerializeAsUKDate;
// Also, if you need to support nullable DateTimes:
JsConfig<DateTime?>.SerializeFn = SerializeAsNullableUKDate;

public static string SerializeAsUKDate(DateTime value)
{
    // or whatever you prefer to specify the format/culture
    return value.ToString("dd/MM/yyyy");
}

public static string SerializeAsNullableUKDate(DateTime? value)
{
    return value.HasValue ? SerializeAsUKDate(value.Value) : null;
}

您可能需要也可能不需要指定DeSerializeFn以确保正确解析日期。ServiceStack.Text 日期反序列化器非常强大。

JsConfig<DateTime>.DeSerializeFn = DeSerializeAsUKDate;

public static DateTime DeSerializeAsUKDate(string value)
{
    // date parsing logic here
    // ServiceStack.Text.Common.DateTimeSerializer has some helper methods you may want to leverage
}
于 2014-03-07T15:11:43.250 回答