I am trying to use interceptions on .Net Core 2.0 WebApi Application by using Autofac but I couldnt succeed it on Controllers. What I try is
First I created a basic webapi which has one default controller(ValuesController). Then I set up the autofac configuration as below. Project is working without any error, but interception doesnt seems to be running. What I am doing wrong ?
Startup.cs
public void ConfigureContainer(ContainerBuilder builder)
{
builder.Register(c => new CallLogger());
builder.RegisterType<ValuesController>()
.EnableClassInterceptors()
.InterceptedBy(typeof(CallLogger));
}
CallLogger.cs
public class CallLogger : IInterceptor
{
public CallLogger()
{
System.Console.WriteLine("XXXXX");
}
public void Intercept(IInvocation invocation)
{
Console.WriteLine($"Calling method {invocation.Method.Name} with parameters {(string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()))}... ");
invocation.Proceed();
Console.WriteLine("Done: result was {0}.", invocation.ReturnValue);
}
}
ValuesController.cs
[Route("api/[controller]")]
[Intercept(typeof(CallLogger))]
public class ValuesController : Controller
{
private readonly ITest _test;
public ValuesController(ITest test)
{
_test = test;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id, [FromHeader(Name = "TenantId")] string tenantId)
{
_test.Log("asdasdasda");
return tenantId + " => " + id;
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}