简体   繁体   中英

Override field name de-serialization in ServiceStack

I have a service which uses autoquery and has a response dto which looks like this

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

}

when I use autoquery without spaces it returns the correct result, but with spaces the autoquery doesnt work http://localhost/search?listid=12345

In the apphost.cs I added the following code

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

}

But still I cannot get the results when I use the underscore. What am I missing?

This AutoQuery test shows AutoQuery supporting a Request DTO with custom alias fields as seen in this AutoQuery Service:

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

Which can be called with this test:

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 has also been updated to look at any matching any aliases on the underlying table so now you can use field conventions on the query table, eg:

[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();

It also supports implicit mapping using the JsConfig.EmitLowercaseUnderscoreNames convention, eg:

JsConfig.EmitLowercaseUnderscoreNames = true;

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

These changes are available from v4.0.41+ that's now available on MyGet .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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