diff options
| author | Luke Pulverenti <luke.pulverenti@gmail.com> | 2016-11-11 14:55:12 -0500 |
|---|---|---|
| committer | Luke Pulverenti <luke.pulverenti@gmail.com> | 2016-11-11 14:55:12 -0500 |
| commit | 406e6cb8132c1b8ade2872d44d7183267dd51ca8 (patch) | |
| tree | f9088ce1219351cee1976ba9fa57ed6341eeed9a /ServiceStack/Host/ContentTypes.cs | |
| parent | f8b8de13b752c49360bbe10502cc067be89937ae (diff) | |
update portable projects
Diffstat (limited to 'ServiceStack/Host/ContentTypes.cs')
| -rw-r--r-- | ServiceStack/Host/ContentTypes.cs | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/ServiceStack/Host/ContentTypes.cs b/ServiceStack/Host/ContentTypes.cs new file mode 100644 index 000000000..22fdc3e50 --- /dev/null +++ b/ServiceStack/Host/ContentTypes.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using MediaBrowser.Model.Services; + +namespace ServiceStack.Host +{ + public class ContentTypes + { + public static ContentTypes Instance = new ContentTypes(); + + public void SerializeToStream(IRequest req, object response, Stream responseStream) + { + var contentType = req.ResponseContentType; + var serializer = GetResponseSerializer(contentType); + if (serializer == null) + throw new NotSupportedException("ContentType not supported: " + contentType); + + var httpRes = new HttpResponseStreamWrapper(responseStream, req) + { + Dto = req.Response.Dto + }; + serializer(req, response, httpRes); + } + + public Action<IRequest, object, IResponse> GetResponseSerializer(string contentType) + { + var serializer = GetStreamSerializer(contentType); + if (serializer == null) return null; + + return (httpReq, dto, httpRes) => serializer(httpReq, dto, httpRes.OutputStream); + } + + public Action<IRequest, object, Stream> GetStreamSerializer(string contentType) + { + switch (GetRealContentType(contentType)) + { + case "application/xml": + case "text/xml": + case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml + return (r, o, s) => ServiceStackHost.Instance.SerializeToXml(o, s); + + case "application/json": + case "text/json": + return (r, o, s) => ServiceStackHost.Instance.SerializeToJson(o, s); + } + + return null; + } + + public Func<Type, Stream, object> GetStreamDeserializer(string contentType) + { + switch (GetRealContentType(contentType)) + { + case "application/xml": + case "text/xml": + case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml + return ServiceStackHost.Instance.DeserializeXml; + + case "application/json": + case "text/json": + return ServiceStackHost.Instance.DeserializeJson; + } + + return null; + } + + private static string GetRealContentType(string contentType) + { + return contentType == null + ? null + : contentType.Split(';')[0].ToLower().Trim(); + } + + } +}
\ No newline at end of file |
