Skip to content

Instantly share code, notes, and snippets.

@starteleport
Last active December 10, 2015 23:48
Show Gist options
  • Save starteleport/4511749 to your computer and use it in GitHub Desktop.
Save starteleport/4511749 to your computer and use it in GitHub Desktop.
ServiceStack ServiceStack\WebHost.Endpoints\Formats\HtmlFormat.cs
public void SerializeToStream(IRequestContext requestContext, object response, IHttpResponse httpRes)
{
var httpReq = requestContext.Get<IHttpRequest>();
if (httpReq != null && AppHost.ViewEngines.Any(x => x.ProcessRequest(httpReq, httpRes, response))) return;
if (requestContext.ResponseContentType != ContentType.Html && httpReq != null
&& httpReq.ResponseContentType != ContentType.JsonReport) return;
var dto = response.ToDto();
var html = dto as string;
if (html == null)
{
// Serialize then escape any potential script tags to avoid XSS when displaying as HTML
var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
json = json.Replace("<", "&lt;").Replace(">", "&gt;");
string url = string.Empty;
if (httpReq != null)
{
url = httpReq.AbsoluteUri
.Replace("format=html", "")
.Replace("format=shtm", "")
.TrimEnd('?', '&');
url += url.Contains("?") ? "&" : "?";
}
var now = DateTime.UtcNow;
string requestName = string.Empty;
if (httpReq != null) requestName = httpReq.OperationName ?? dto.GetType().Name;
html = GetHtmlTemplate()
.Replace("${Dto}", json)
.Replace("${Title}", string.Format(TitleFormat, requestName, now))
.Replace("${MvcIncludes}", MiniProfiler.Profiler.RenderIncludes().ToString())
.Replace("${Header}", string.Format(HtmlTitleFormat, requestName, now))
.Replace("${ServiceUrl}", url);
}
var utf8Bytes = html.ToUtf8Bytes();
httpRes.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment