Skip to content

Commit

Permalink
Commit logger in OA.WebAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
programmingexperience committed Jun 12, 2017
1 parent 351e2a0 commit 6395bea
Show file tree
Hide file tree
Showing 8 changed files with 123 additions and 57 deletions.
1 change: 0 additions & 1 deletion OnionArchitecture/OA.Service/Helpers/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,5 @@ public static string GetIpAddress()
}
return localIp;
}

}
}
14 changes: 14 additions & 0 deletions OnionArchitecture/OA.Service/Interfaces/ILoggerSrvc.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using OA.Data.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OA.Service.Interfaces
{
public interface ILoggerSrvc
{
void Insert(Log log);
}
}
7 changes: 6 additions & 1 deletion OnionArchitecture/OA.Service/OA.Service.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,18 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Helpers\Helper.cs" />
<Compile Include="Interfaces\ILoggerSrvc.cs" />
<Compile Include="Interfaces\IOrderSrvc.cs" />
<Compile Include="Interfaces\IUserSrvc.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\LoggerSrvc.cs" />
<Compile Include="Services\OrderSrvc.cs" />
<Compile Include="Services\UserSrvc.cs" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Folder Include="Enumerations\" />
<Folder Include="Extensions\" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
Expand Down
25 changes: 25 additions & 0 deletions OnionArchitecture/OA.Service/Services/LoggerSrvc.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OA.Service.Interfaces;
using OA.Repo.UoW;
using OA.Data.Model;

namespace OA.Service.Services
{
public class LoggerSrvc : ILoggerSrvc
{
private readonly IGenericUoW _UoW;
public LoggerSrvc(IGenericUoW UoW)
{
_UoW = UoW;
}
public void Insert(Log log)
{
_UoW.GenericRepository<Log>().Insert(log);
_UoW.SaveChanges();
}
}
}
5 changes: 5 additions & 0 deletions OnionArchitecture/OA.WebAPI/ActionFilters/Filters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Net;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using OA.Service.Interfaces;

namespace OA.WebAPI.ActionFilters
{
Expand All @@ -12,10 +13,14 @@ public class ModelStateFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{

if (!actionContext.ModelState.IsValid)
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
/// <summary>
///
/// </summary>
public class UnhandledExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
Expand Down
4 changes: 2 additions & 2 deletions OnionArchitecture/OA.WebAPI/App_Start/FilterConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public static void RegisterGlobalFilters(GlobalFilterCollection filters)
filters.Add(new HandleErrorAttribute());

// Custom action filter
filters.Add(new ModelStateFilter());
filters.Add(new UnhandledExceptionFilter());
//filters.Add(new ModelStateFilter());
//filters.Add(new UnhandledExceptionFilter());
}
}
}
6 changes: 6 additions & 0 deletions OnionArchitecture/OA.WebAPI/App_Start/WebApiConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using OA.Service.Services;
using OA.Repo.UoW;
using OA.WebAPI.Handlers;
using OA.WebAPI.ActionFilters;

namespace OA.WebAPI
{
Expand All @@ -33,8 +34,13 @@ public static void Register(HttpConfiguration config)
);

// Handler for request and response logging.
//config.MessageHandlers.Add(new LogRequestAndResponseHandler());

config.Filters.Add(new ModelStateFilter());
config.Filters.Add(new UnhandledExceptionFilter());
config.MessageHandlers.Add(new LogRequestAndResponseHandler());


// Web API configuration and services
var container = new UnityContainer();
//container.RegisterType<IGenericRepository, GenericRepository>(new HierarchicalLifetimeManager());
Expand Down
118 changes: 65 additions & 53 deletions OnionArchitecture/OA.WebAPI/Handlers/Handler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,66 +9,78 @@
using System.Diagnostics;
using OA.Data.Model;
using OA.Service.Helpers;


using OA.Service.Interfaces;
using OA.Repo.UoW;
using OA.Service.Services;

namespace OA.WebAPI.Handlers
{
public class LogRequestAndResponseHandler : DelegatingHandler
{
//protected override async Task<HttpResponseMessage> SendAsync(
// HttpRequestMessage request, CancellationToken cancellationToken)
//{
// // log request body
// string requestBody = await request.Content.ReadAsStringAsync();
// Trace.WriteLine(requestBody);

// var log = new Log
// {
// Id = 1,
// RequestIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Helper.GetIpAddress(),
// RequestUri = request.RequestUri.ToString(),
// RequestMethod = request.Method.Method,
// RequestPostData = Helper.Encrypt(requestBody),
// RequestTimestamp = DateTime.Now
// };


// // let other handlers process the request
// var result = await base.SendAsync(request, cancellationToken);

// if (result.Content != null)
// {
// // once response body is ready, log it
// var responseBody = await result.Content.ReadAsStringAsync();
// Trace.WriteLine(responseBody);
private readonly ILoggerSrvc _loggerSrvc;
/// <summary>
///
/// </summary>
public LogRequestAndResponseHandler()
{
IGenericUoW _UoW = new GenericUoW();
ILoggerSrvc loggerServiceParam = new LoggerSrvc(_UoW);
this._loggerSrvc = loggerServiceParam;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{

// log request body
string requestBody = await request.Content.ReadAsStringAsync();
Trace.WriteLine(requestBody);

// object content;
// string errorMessage = null;
// string messageDetail = null;
// if (result.TryGetContentValue(out content) && !result.IsSuccessStatusCode)
// {
// HttpError error = content as HttpError;
// if (error != null)
// {
// messageDetail = error.MessageDetail;
// errorMessage = error.Message;
// errorMessage = string.Concat(errorMessage, error.ExceptionMessage, error.StackTrace);
// }
// }
// if (messageDetail != "No route data was found for this request.")
// {
// log.ResponseStatusCode = (int)result.StatusCode;
// log.ResponseReasonPhrase = result.ReasonPhrase;
// log.ResponseErrorMessage = errorMessage;
// log.ResponseTimestamp = DateTime.Now;
// IGenericRepository<Log> repository = new GenericRepository<Log>();
// await repository.Insert(log);
// }
// }
var log = new Log
{
UserId = 1,
RequestIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Helper.GetIpAddress(),
RequestUri = request.RequestUri.ToString(),
RequestMethod = request.Method.Method,
RequestPostData = Helper.Encrypt(requestBody),
RequestTimestamp = DateTime.Now
};
// let other handlers process the request
var result = await base.SendAsync(request, cancellationToken);
if (result.Content != null)
{
// once response body is ready, log it
var responseBody = await result.Content.ReadAsStringAsync();
Trace.WriteLine(responseBody);

// return result;
//}
object content;
string errorMessage = null;
string messageDetail = null;
if (result.TryGetContentValue(out content) && !result.IsSuccessStatusCode)
{
HttpError error = content as HttpError;
if (error != null)
{
messageDetail = error.MessageDetail;
errorMessage = error.Message;
errorMessage = string.Concat(errorMessage, error.ExceptionMessage, error.StackTrace);
}
}
if (messageDetail != "No route data was found for this request.")
{
log.ResponseStatusCode = Convert.ToInt32(result.StatusCode).ToString();
log.ResponseReasonPhrase = result.ReasonPhrase;
log.ResponseErrorMessage = errorMessage;
log.ResponseTimestamp = DateTime.Now;
_loggerSrvc.Insert(log);
}
}
return result;
}
}
}

0 comments on commit 6395bea

Please sign in to comment.