Skip to content

Instantly share code, notes, and snippets.

@PeteGoo
Created April 9, 2012 00:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PeteGoo/2340497 to your computer and use it in GitHub Desktop.
Save PeteGoo/2340497 to your computer and use it in GitHub Desktop.
ProtobufNetFormatter for Web API
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using WebApi.OData.WebApp.Infrastructure;
namespace WebApi.OData.WebApp {
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Add the protobuf formatter to the web api configuration list of formatters
HttpConfiguration configuration = GlobalConfiguration.Configuration;
configuration.Formatters.Add(new ProtobufNetFormatter());
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
}
}
}
using System;
using System.IO;
using System.Net;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using ProtoBuf;
namespace WebApi.OData.WebApp.Infrastructure {
public class ProtobufNetFormatter : MediaTypeFormatter {
public ProtobufNetFormatter() {
// Fill out the mediatype and encoding we support
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-protobuf"));
}
protected override bool CanReadType(Type type) {
if (type == typeof(IKeyValueModel)) {
return false;
}
return true;
}
protected override bool CanWriteType(Type type) {
return true;
}
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) {
// Create task reading the content
return Task.Factory.StartNew(() => Serializer.NonGeneric.Deserialize(type, stream));
}
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) {
// Create task writing the serialized content
return Task.Factory.StartNew(() => Serializer.NonGeneric.Serialize(stream, value));
}
}
}
using System;
using Linq2Rest.Implementations;
namespace WebApi.OData.Common.Infrastructure {
public class ProtoBufRestClient : RestClientBase {
public ProtoBufRestClient(Uri uri) : base(uri, "application/x-protobuf") { }
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Linq2Rest.Provider;
using ProtoBuf;
namespace WebApi.OData.Common.Infrastructure {
public class ProtobufSerializerFactory : ISerializerFactory {
public ISerializer<T> Create<T>() {
return new ProtobufSerializer<T>();
}
public class ProtobufSerializer<T> : ISerializer<T> {
public T Deserialize(string input) {
using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(input))) {
return Serializer.Deserialize<T>(stream);
}
}
public IList<T> DeserializeList(string input) {
using (Stream stream = new MemoryStream(Encoding.Default.GetBytes(input))) {
return Serializer.Deserialize<IList<T>>(stream);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment