Skip to content

Instantly share code, notes, and snippets.

@GraemeF
Created July 30, 2011 20:02
Show Gist options
  • Save GraemeF/1115940 to your computer and use it in GitHub Desktop.
Save GraemeF/1115940 to your computer and use it in GitHub Desktop.
Request/Response extensions
public static class RequestExtensions
{
public static string AsString(this RequestStream requestStream)
{
return new StreamReader(requestStream).ReadToEnd();
}
public static XDocument AsXml(this RequestStream requestStream)
{
return XDocument.Load(requestStream);
}
public static bool AsksForJson(this Request request)
{
return request.AsksFor(Schema.ContentTypes.JsonContentTypes);
}
public static bool AsksForJsonp(this Request request)
{
return request.AsksFor(Schema.ContentTypes.JsonpContentTypes) ||
request.QueryParameterNames().Contains("callback");
}
public static TDto BodyAsDto<TDto>(this Request request)
{
var bodyReader = new StreamReader(request.Body);
return request.SuppliesJson()
? new JavaScriptSerializer().Deserialize<TDto>(bodyReader.ReadToEnd())
: (TDto)new XmlSerializer(typeof(TDto)).Deserialize(bodyReader);
}
public static IEnumerable<string> QueryParameterNames(this Request request)
{
return request.Query.GetDynamicMemberNames();
}
public static bool Supplies(this Request request, IEnumerable<string> contentTypes)
{
return ContentTypesMatchAnyRequestHeader(request.Headers["Content-Type"], contentTypes);
}
public static bool SuppliesJson(this Request request)
{
return request.Supplies(Schema.ContentTypes.JsonContentTypes);
}
private static bool AnyContentTypeIsAccepted(IEnumerable<string> contentTypes, string acceptedType)
{
return contentTypes.Any(acceptedType.Contains);
}
private static bool AsksFor(this Request request, IEnumerable<string> contentTypes)
{
return ContentTypesMatchAnyRequestHeader(request.Headers["Accept"], contentTypes);
}
private static IEnumerable<string> ContentTypesInAcceptHeader(string acceptHeaderValue)
{
return acceptHeaderValue.Split(',');
}
private static bool ContentTypesMatchAnyRequestHeader(IEnumerable<string> headerValues,
IEnumerable<string> contentTypes)
{
return headerValues
.Any(acceptHeaderValue => ContentTypesInAcceptHeader(acceptHeaderValue)
.Any(acceptedType => AnyContentTypeIsAccepted(contentTypes,
acceptedType)));
}
}
public static class ResponseExtensions
{
public static Response AsBody<TModel>(this IResponseFormatter formatter, Request request, TModel model)
{
return request.AsksForJsonp()
? formatter.AsJsonp(model, (string)request.Query.callback)
: request.AsksForJson()
? formatter.AsJson(model)
: formatter.AsXml(model);
}
public static Response AsJsonp<TModel>(this IResponseFormatter formatter, TModel model, string jsonCallback)
{
return new JsonpResponse<TModel>(model, jsonCallback);
}
public static Response AsString(this IResponseFormatter formatter, string body)
{
return new Response
{
Contents = stream => WriteContentToStream(stream, body)
};
}
public static Response CacheableFor(this Response response, TimeSpan timeSpan)
{
response.Headers["Cache-Control"] = string.Format("max-age={0}", (int)timeSpan.TotalSeconds);
return response;
}
public static string IfNoneMatch(this Request request)
{
IEnumerable<string> value = request.Headers["If-None-Match"].ToList();
return value.Any()
? string.Join("", value)
: null;
}
public static Response Uncacheable(this Response response)
{
response.Headers["Cache-Control"] = "No-cache";
return response;
}
public static Response WithETag(this Response response, string etag)
{
response.Headers["ETag"] = etag;
return response;
}
public static Response WithStatusCode(this Response response, HttpStatusCode statusCode)
{
response.StatusCode = statusCode;
return response;
}
private static Response AsJson<TModel>(this IResponseFormatter formatter, TModel model)
{
Response response = FormatterExtensions.AsJson(formatter, model);
response.ContentType = "application/json";
return response;
}
private static Response AsXml<TModel>(this IResponseFormatter formatter, TModel model)
{
return new XmlResponse<TModel>(model, "application/xml");
}
private static void WriteContentToStream(Stream stream, string content)
{
var writer = new StreamWriter(stream);
writer.Write(content);
writer.Flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment