Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- return new HttpResponseMessage
- {
- Content = new ObjectContent<string>("Hello world", new JsonMediaTypeFormatter()),
- StatusCode = HttpStatusCode.OK
- };
- public class VMRegistrant
- {
- public int MerchantId { get; set; }
- public string Email { get; set; }
- }
- public HttpResponseMessage CreateRegistrant(VMRegistrant registrant)
- {
- // Save registrant in db...
- }
- public IHttpActionResult Foo()
- {
- var bar = new Bar { Message = "Hello" };
- return Request.CreateResponse(HttpStatusCode.OK, bar, new MediaTypeHeaderValue("application/json"));
- }
- public IHttpActionResult Foo()
- {
- var bar = new Bar { Message = "Hello" };
- return Content(HttpStatusCode.OK, bar, new JsonMediaTypeFormatter(), new MediaTypeHeaderValue("application/json"));
- }
- public async Task<IHttpActionResult> FooAsync()
- {
- var json = await Request.Content.ReadAsStringAsync();
- var content = JsonConvert.DeserializeObject<VMRegistrant>(json);
- }
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
- public class ChangeFormatterAttribute : ActionFilterAttribute
- {
- private IEnumerable<MediaTypeFormatter> oldFormatters;
- private MediaTypeFormatter desiredFormatter;
- public ChangeFormatterAttribute(Type formatterType)
- {
- this.desiredFormatter = Activator.CreateInstance(formatterType) as MediaTypeFormatter;
- }
- public override void OnActionExecuting(HttpActionContext actionContext)
- {
- var formatters = actionContext.ControllerContext.Configuration.Formatters;
- oldFormatters = formatters.ToList();
- formatters.Clear();
- formatters.Add(desiredFormatter);
- base.OnActionExecuting(actionContext);
- }
- public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
- {
- var formatters = actionExecutedContext.ActionContext.ControllerContext.Configuration.Formatters;
- formatters.Clear();
- formatters.AddRange(oldFormatters);
- base.OnActionExecuted(actionExecutedContext);
- }
- }
- [ChangeFormatterAttribute(typeof(JsonMediaTypeFormatter))]
- public class HomeController : ApiController
- {
- public string Get()
- {
- return "ok";
- }
- }
- // ...
- [ChangeFormatterAttribute(typeof(XmlMediaTypeFormatter))]
- public class ValuesController : ApiController
- {
- public string Get()
- {
- return "ok";
- }
- }
- public class Dog
- {
- public string Name { get; set; }
- }
- public class DogMediaTypeFormatter : JsonMediaTypeFormatter
- {
- public override bool CanReadType(Type type)
- {
- return type == typeof (Dog);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement