title: ASP.NET WebAPI filter data by user property
body: <p>ASP.NET WebAPI 2.1</p>
  
  <p>Here is my scenario:</p>
  
  <ul>
  <li>new user is registering (one of the Identity properties is CustomerID - hidden from user, default NULL)</li>
  <li>Admin is updating CustomerID with correct primary key from Customers table and assigning Role "Customer" to registered user. From now on user should be able to see all his Invoices, orders, etc.</li>
  </ul>
  
  <p>How can I filter all web API calls for Invoices, Orders, etc with CustomerID ?</p>
  
  <p>I was searching a lot and I couldn't find any samples. I'd really appreciate if some will point me to right direction and/or a sample code.</p>
  
  <p>Below is my controller:</p>
  
  <pre><code>public class invoicesController : ApiController
  {
      private myEntities db new db1Entities();
  
      // GET api/invoices
      public IQueryable&lt;invoices&gt; Getinvoices()
      {
             // here (I guess) I need to add a filter by CustomerID
                 // first get CustomerID from logged In User
  
              return db.invoices;
      }
  
       // GET api/invoices/5
      [ResponseType(typeof(invoices))]
      public IHttpActionResult Getinvoices(int id)
       {
          invoices invoices_by_id = db.invoices.Find(id);
          if (invoices_by_id == null)
          {
                          return NotFound();
          }       
         return Ok(invoices_by_id);
      }   
  }
  </code></pre>
  
  <p>OK. I got it working but I think there must a better way to access user property...anyone ?</p>
  
  <pre><code>// Instantiate the UserManager in ASP.Identity system to look up the user in the system
  // ApplicationUser class is defined in IdentityModels.cs, same as ApplicationDbContext
  var manager = new UserManager&lt;ApplicationUser&gt;(new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext()));
  //Get the User object
  var currentUser = manager.FindById(User.Identity.GetUserId());
  //Get the profile information about the user
  int? userCustomerID = currentUser.customerID;
  </code></pre>
  
  <p>And in controller I just changed last line:</p>
  
  <pre><code>return View(db.invoices.Where(i =&gt; i.CustomerID == userCustomerID).ToList());
  </code></pre>