Skip to content

Instantly share code, notes, and snippets.

@anujb
Created August 7, 2011 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anujb/3b18a58922fdd8d5a963 to your computer and use it in GitHub Desktop.
Save anujb/3b18a58922fdd8d5a963 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ServiceStack.Text;
using Devnos.Core.DataAccess.Model;
using Munq.MVC3;
namespace Devnos.Core.Web.ActionFilters
{
public class ParamSerializationFilter : ActionFilterAttribute
{
enum AllowedMethods
{
GET,
POST,
PUT,
}
private IModelTypes ModelTypes { get; set; }
public ParamSerializationFilter()
{
ModelTypes = MunqDependencyResolver.Container.Resolve<IModelTypes>();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!Enum.GetNames(typeof(AllowedMethods)).Any(n => n == filterContext.HttpContext.Request.HttpMethod))
throw new InvalidOperationException("Invalid Request: HttpMethod");
foreach (var param in filterContext.ActionDescriptor.GetParameters())
{
if (ModelTypes.Contains(param.ParameterType))
{
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty) == ("application/json"))
{
filterContext.ActionParameters[param.ParameterName] =
JsonSerializer.DeserializeFromStream(param.ParameterType, filterContext.HttpContext.Request.InputStream);
}
else if (filterContext.HttpContext.Request.ContentType.Contains("xml"))
{
filterContext.ActionParameters[param.ParameterName] =
XmlSerializer.DeserializeFromStream(param.ParameterType, filterContext.HttpContext.Request.InputStream);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment