Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack and returning a stream

Tags:

servicestack

I have just started to use ServiceStack which is an amazing library.

However, I have a business requirement where we must return xml and json where the xml must be in specific format.

For example we have existing customers that expect xml of the format:

<service name="service1" type="audio" .../>

so basically a bunch of attributes.

I know that ServiceStack uses concepts of DTOs and uses the DataContractSerializer which returns xml elements rather than in the form above with xml attributes.

I still want to use the DTOs for requests (passing in application/xml or application/json in the Accept header) and I can then create my own xml strings or json strings and then return them as :

string result = "....xml or json string...";
return new MemoryStream(Encoding.UTF8.GetBytes(result));

where the result string could be an xml string or a json string.

I noticed in fiddler the response Content-Type as text/html.

With the approach I am using, am I violating any REST principles? Will there be issues with the Content-Type as it is currently (text/html)?

If I do use this approach it does solve the business requirements.

Edit

I found that I can return a httpResult as :

return new HttpResult(
         new MemoryStream(Encoding.UTF8.GetBytes(result)), "application/xml");

which gives the correct content-type.

So, is this the right way or will I have issues if I go down this route?

like image 321
JD. Avatar asked Apr 06 '12 07:04

JD.


1 Answers

Yes returning an IHttpResult will allow you to control the exact payload, Content-Type and other HTTP Headers as you wish.

Also you're not limited to returning a stream, i.e. you can use the HttpResult to return an xml string with a different Content-Type.

Here are some links that better demonstrate what's possible with ServiceStack return types:

  • How ServiceStack supports plain C# string, binary, stream, IStreamWriter, etc return types
  • An example of using CORS to set global or per-service custom HTTP Headers
  • Different ways of returning an Image from a ServiceStack service
  • Multiple options for returning HTML

You can also return a static File using a FileInfo object, with an optional parameter to return the file as an attachment which will prompt the user to download the file rather than attempt to view it in the browser with:

return new HttpResult(new FileInfo("~/static-response.xml"), asAttachment:true);
like image 171
mythz Avatar answered Sep 20 '22 12:09

mythz