I have a web api controller and I need to audit the user that did the changes. Currently I do the following:
public class CustomerController : ApiController
{
private readonly ICustomerService customerService;
private bool userSet = false;
public CustomerController(ICustomerService customerService)
{
this.customerService = customerService;
}
[NonAction]
private SetUser(string userId)
{
if (userSet)
return;
//Get user from repository... here just for the example
var User = GetUser(userId);
customerService.SetUser(user);
userSet = true;
}
public Customer GetCustomer()
{
CookieHeaderValue cookie = Request.Headers.GetCookies("userId").FirstOrDefault();
SetUser(cookie["userId"].Value);
//code...
}
public int PostCustomer(Customer customer)
{
CookieHeaderValue cookie = Request.Headers.GetCookies("userId").FirstOrDefault();
SetUser(cookie["userId"].Value);
//code...
}
public void PutCustomer(int id, Customer customer)
{
CookieHeaderValue cookie = Request.Headers.GetCookies("userId").FirstOrDefault();
SetUser(cookie["userId"].Value);
//code..
}
public void DeleteCustomer(int id)
{
CookieHeaderValue cookie = Request.Headers.GetCookies("userId").FirstOrDefault();
SetUser(cookie["userId"].Value);
//code...
}
}
I am getting the userid that is in the request, and I set the user in the service. However, I have many more controllers and these have many more actions.
Is this the way to do it or is there any alternative that I can set the userId for the 'session' (although not using the standard Session in Web API)?
userIdinside aClaimand retrieve it in all the actions using theIdentity.