覆盖ServiceStack中的字段名称反序列化

时间:2015-06-15 23:54:12

标签: c# servicestack

我有一个使用autoquery的服务,并且有一个响应dto,看起来像这样

[DataContract(Name = "list_item", Namespace = "")]
public class ListItem
{
    [DataMember(Name = "list_id",)]
    public String ListId { get; set; }
    [DataMember(Name = "first_name")]
    public String FirstName  { get; set; }

}

当我使用不带空格的autoquery时,它返回正确的结果,但是使用空格时autoquery不起作用 http://localhost/search?listid=12345

在apphost.cs中我添加了以下代码

 private void ConfigSerializer(Container container)
    {                       
        JsConfig.PropertyConvention = PropertyConvention.Lenient;
        JsConfig.EmitLowercaseUnderscoreNames = true;

}

但是当我使用下划线时,我仍然无法得到结果。 我错过了什么?

1 个答案:

答案 0 :(得分:0)

AutoQuery test显示AutoQuery支持具有自定义别名字段的请求DTO,如此AutoQuery服务中所示:

[DataContract]
[Route("/rockstars")]
public class QueryRockstars : QueryBase<Rockstar>
{
    [DataMember(Name = "first_name")]
    public string FirstName { get; set; }
}

可以通过此测试调用:

var request = new QueryRockstars { FirstName = "Jimi" };

//QueryString used:
Assert.That(request.ToGetUrl(), 
    Is.EqualTo("/rockstars?first_name=Jimi"));

var response = client.Get(request);

Assert.That(response.Results.Count, Is.EqualTo(1));
Assert.That(response.Results[0].FirstName, Is.EqualTo("Jimi"));

ServiceStack也已更新,以查看基础表上任何匹配的任何别名,现在您可以在查询表上使用字段约定,例如:

[Route("/search")]
public class QueryPerson : QueryBase<Person> {}

[DataContract]
public class Person
{
    [DataMember]
    public int Id { get; set; }

    [DataMember(Name = "first_name")]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}

var response = "http://example.org/search"
    .AddQueryParam("first_name", "Jimi")
    .GetJsonFromUrl()
    .FromJson<QueryResponse<Person>>();

response.PrintDump();

它还支持使用JsConfig.EmitLowercaseUnderscoreNames约定的隐式映射,例如:

JsConfig.EmitLowercaseUnderscoreNames = true;

var response = "http://example.org/search"
    .AddQueryParam("last_name", "Hendrix")
    .GetJsonFromUrl()
    .FromJson<QueryResponse<Person>>();

这些更改可从 v4.0.41 + 获得,现在为available on MyGet