根据当前经过身份验证的用户获取资源

时间:2013-10-01 14:42:30

标签: servicestack

如果我使用ServiceStack进行操作,例如GetOrders:

[Route("/orders")]
public class GetOrders : IReturn<List<Order>> { }

然后我在服务中使用它:

[Authenticate]
public class OrdersService : Service
{
    public object Get(GetOrders request)
    {
        var dbOrders = Db.Select<Order>().ToList();
        // What I want is to only get orders of the user making the request
        // var dbOrders = Db.Select<Order>().Where(x=>x.UserId == ??).ToList();
        return dbOrders;
    }   
}

假设我的Order实体有一个名为UserId的属性,我该如何访问当前登录的用户,然后我可以将其映射到UserId并仅选择来自我的数据库?

1 个答案:

答案 0 :(得分:3)

您可以通过SessionAs<T>方法访问您键入的UserSession,例如:

[Authenticate]
public class OrdersService : Service
{
    public object Get(GetOrders request)
    {
        var userSession = base.SessionAs<AuthUserSession>();
        var userId = int.Parse(userSession.UserAuthId);
        var dbOrders = Db.Select<Order>(x => x.UserId == userId);
        return dbOrders;
    }   
}