aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Web/Controllers/JsonController.cs
blob: 9d9016d5ac5a4609f19bde3a3e55c090e96d0d86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Tango.Logging;

namespace Tango.Web.Controllers
{
    public class JsonController : ApiController
    {
        protected LogManager LogManager { get; private set; }

        public JsonController()
        {
            LogManager = LogManager.Default;
        }

        public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext context, CancellationToken cancellationToken)
        {
            string controllerName = String.Empty;
            string actionName = String.Empty;

            try
            {
                var routeData = HttpContext.Current.Request.RequestContext.RouteData;
                actionName = routeData.Values["action"].ToString();
                controllerName = routeData.Values["controller"].ToString();
            }
            catch { }

            try
            {
                String request = String.Empty;

                try
                {
                    request = context.Request.Content.ReadAsStringAsync().Result;
                }
                catch {}

                LogManager.Log($"Request Received on {controllerName + "/" + actionName}: \n{request}");

                var result = await base.ExecuteAsync(context, cancellationToken);
                return result;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"An error occurred while processing the request message on {controllerName + "/" + actionName}.");

                HttpStatusCode code = HttpStatusCode.InternalServerError;

                if (ex is ArgumentException)
                {
                    code = HttpStatusCode.BadRequest;
                }
                else if (ex is AuthenticationException)
                {
                    code = HttpStatusCode.Unauthorized;
                }

                throw new HttpResponseException(Request.CreateErrorResponse(code, ex.ToString()));
            }
        }
    }
}