我有一个web api控制器,我需要审核做出更改的用户。目前我执行以下操作:Web Api和会话变量?
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...
}
}
我得到请求中的用户标识,并将用户设置在服务中。但是,我有更多的控制器,而且这些控制器有更多的操作。
这是做到这一点的方法,或者是否有其他方法可以为'会话'设置userId(虽然不使用Web API中的标准会话)?
你可以存储'userId'一个'里面索赔'并使用'Identity'在所有动作中检索它。 –