我正在尝试记录/保留我的所有请求/响应,并认为我尝试使用全局属性,但是当我实际使用 repo 时,它是空的吗?这可能吗?
还有其他方法可以实现我想要做的事情吗?
谢谢你,斯蒂芬
属性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class LogRequestAttribute : RequestFilterAttribute
{
public IRepository Repo { get; set; }
public LogRequestAttribute(ApplyTo applyTo)
: base(applyTo)
{
this.Priority = -200;
}
public LogRequestAttribute()
: this(ApplyTo.All) {}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
try
{
// Convert the req obj into something that can be persisted...
Repo.LogRequest("Logging the rquest");
}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError(ex.ToString());
}
}
}
应用主机配置
public override void Configure(Container container)
{
//Set JSON web services to return idiomatic JSON camelCase properties
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
//Show StackTrace in Web Service Exceptions
SetConfig(new EndpointHostConfig { DebugMode = true });
//Register any dependencies you want injected into your services
container.Register<ICacheClient>(new MemoryCacheClient());
/* // Redis
container.Register<IRedisClientsManager>(c => new PooledRedisClientManager());
container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>()));*/
container.Register<IRepository>(new Repository());
container.Register<IBusinessService>(new BusinessService());
//Configure Custom User Defined REST Paths for your services
/*ConfigureServiceRoutes();*/
//Add a request filter to check if the user has a session initialized
/*this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
var sessionId = httpReq.GetCookieValue("user-session");
if (sessionId == null)
{
httpResp.ReturnAuthRequired();
}
});*/
RequestFilters.Add((httpReq, httpResp, requestDto) => new LogRequestAttribute().Execute(httpReq, httpResp, requestDto));
}
存储库
public interface IRepository
{
void LogRequest(string request);
void LogResponse(string request);
}
public class Repository : IRepository
{
private static readonly ILog Log = LogManager.GetLogger("API.Repository");
public Repository()
{
}
public void LogRequest(string request)
{
Log.Debug(request);
}
public void LogResponse(string request)
{
Log.Debug(request);
}
}
更新
//Add a 'global' request filter
this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
/* Code here */
});
//Add a 'global' response filter
this.ResponseFilters.Add((httpReq, httpResp, responseDto) =>
{
/* Code here */
});