Purpose of IReturn and IReturnVoid within JsonServ

2019-04-13 13:07发布

问题:

Is there a reason why I need to supply IReturn or IReturnVoid references to ServiceStack's JsonServiceClient.Get? There must be a good reason (I'm quite new to the framework) but I don't understand why I have to convert my objects to IReturn wrappers or make them ServiceStack dependant.

I have read those posts but couldn't find the explaination I am looking for (only workarounds):

  • ServiceStack: JsonServiceClient usage without IReturn in DTO
  • ServiceStack IReturn

Thanks!

回答1:

JSON is an untyped data format. Well, there are string and numeric, arrays and key/value pairs - that's about it.

JSON over HTTP doesn't give any type information.

ServiceStack, just like most other RESTful services doing HTTP+JSON, will work just like other services written in other languages - pass JSON back and forth.

Adding IReturn to your service methods will not make your services dependent on ServiceStack - you can use any other HTTP client to make a request and get back JSON in the response.

What is does give you additionally is the option to use a "strongly-typed" http client (JsonServiceClient), which will automatically map to the same .NET type on the client as there is on the server side. So if you want to write a native C#/.NET client for your services, it is incredibly easy.

At the same time, if you or other clients want to write general "untyped" web service clients, those will also work as expected.

Here's how i like to think of it, using ajax client, untyped http+json web service client, and ServiceStack client:

Generic Web Browser:

  • Request (JSON) -> HTTP -> ServiceStack Service
  • Response (JSON) <- HTTP <- ServiceStack Service

Generic HTTP Client:

  • Request (JSON) -> HTTP -> ServiceStack Service
  • Response (JSON) <- HTTP <- ServiceStack Service

ServiceStack's JsonServiceClient:

  • Request (JSON x/.NET type info) -> HTTP -> ServiceStack Service IReturn
  • Response (JSON x/.NET type info) <- HTTP <- ServiceStack Service IReturn

Typically, you would reference the DTO type information from the client and the server project in a *.ServiceModel assembly, which you can use on both ends. Since any type info for DTOs and services are 'in there', the client will know how to deserialize the JSON to the correct type. IReturn is a 'marker' (metadata) on the object - an older SS API used different interfaces to do the same thing, but with more verbosity and less flexibility (different returns for REST vs SOAP it seems).

Also note, your DTOs do not need to implement IReturn - so they do not need to be SS-dependent. I prefer to use IReturn only on "operation" or communication DTOs - those which are passing parameters. I like to keep the DTOs which map to database tables (i.e. - OrmLite) without the IReturn dependency.

https://github.com/ServiceStack/ServiceStack/wiki/C%23-client