I am performing model validation in my controllers, but the second business validation should take place at the service / business level. Usually this is due to user rights: Does the current user have access to customer / order information that he is trying to get or publish?
My first (and working) approach is to pass either the entire User instance or its Id (by calling User.Identity.GetUserId() ), which would be sufficient in most cases - not all the time. So I will have something like this:
public IHttpActionResult Get(int id) { try { var customer = customerService.GetById(id, userId); return Ok(customer); } catch (BusinessLogicException e) { return CreateErrorResponse(e); } }
But I do not really like the fact that with this approach I will have to include an additional parameter in almost every call of my service level. If I call the GetById() method, I want to get something by providing an identifier, not an identifier and a user identifier.
A simple workaround would be something in this direction that also works:
public IHttpActionResult Get(int id) { customerService.SetCurrentUser(User.Identity.GetUserId()); try { var customer = customerService.GetById(id); return Ok(customer); } catch (BusinessLogicException e) { return CreateErrorResponse(e); } }
But instead of making a separate call to set the current user, I would like it to be done automatically every time the service is called. How can i do this?
This is what my service looks like:
public class CustomerService : EntityService<Customer>, ICustomerService { public string UserId; IContext context; public CustomerService(IContext context) : base(context) { this.context = context; this.dbSet = context.Set<Customer>(); } public void SetCurrentUser(string userId) { UserId = userId; } public DTO.Customer GetById(int id) { if (!IsAccessibleByUser(id)) { throw new BusinessLogicException(ErrorCode.UserError, "UserId: " + UserId); } return dbSet.FirstOrDefault(x => x.Id == id).ToDto<Customer, DTO.Customer>(); } public bool IsAccessibleByUser(int id) { return context.UsersAPI.Any(a => a.AspNetUsersID == UserId); } }
source share