PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 3ms RepoModel.GetById 38ms app.codeStats 0ms

/src/Server/DeviceHive.API/Filters/HttpCreatedResponseAttribute.cs

https://github.com/oryol/devicehive-.net
C# | 31 lines | 30 code | 1 blank | 0 comment | 5 complexity | bfa2fde6b7bcc29f6c51a6ad72ef68f8 MD5 | raw file
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Net;
 5using System.Web.Http.Filters;
 6using System.Web.Http.Routing;
 7using Newtonsoft.Json.Linq;
 8
 9namespace DeviceHive.API.Filters
10{
11    public class HttpCreatedResponseAttribute : ActionFilterAttribute
12    {
13        public override void OnActionExecuted(HttpActionExecutedContext context)
14        {
15            if (context.Response != null && context.Response.IsSuccessStatusCode)
16            {
17                context.Response.StatusCode = HttpStatusCode.Created;
18                context.Response.Content.ReadAsStringAsync().ContinueWith(task =>
19                    {
20                        var result = JObject.Parse(task.Result);
21                        if (result["id"] != null)
22                        {
23                            var controller = context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
24                            var route = new UrlHelper(context.Request).Route(null, new { controller = controller, id = result["id"] });
25                            context.Response.Headers.Location = new Uri(context.Request.RequestUri, route);
26                        }
27                    }).Wait();
28            }
29        }
30    }
31}