Acessing username in the web api controller when the database table stores the user as a whole

Inside some api web controllers, I would like to access the User, as indicated in this answer: https://stackoverflow.com/a/316618/

sample code from answer ...

[Authorize] public List<Product> GetProductsFromId() { string username = User.Identity.Name; return _productService.GetProductsFromUsername(username); } 

The asp_net membership tables in my script are on a different database server than the database server on which the application is running. The database for the application has its own Users table with an IDENTITY column as the Primary Key in the Users table, and then other tables, which include the CreatedByUserID and UpdatedByUserID columns, are integers based on the IDENTITY column in the user table.

The problem is that if operations like CRUD depend on updating the user in tables like INTEGER , just one access to the username is not enough; we should still get this username corresponding to UserID .

This can be done with another connection in the Users table, but it seems a bit shabby. What would be the best way to solve this problem?

0
source share
1 answer

From the perspective of the ASP.NET Web API, using the membership provider and the FormsAuthentication pre-built form is already kludgy, so why not join? :) In any case, if your web API is consumed only by web clients and FA is cool, you can use UserData from the FA ticket to enter the user ID. Thus, you do not need to get an identifier each time hitting your database. But you will need to create your ticket yourself and not be allowed to do this by default because of the box. Then, in the PostAuthenticateRequest event, you can read the user ID from the ticket and set it in the ID. Of course, you need to create your own identifier for this using the ID property, or if you are using .NET 4.5, you can use FormsIdentity, but you can use the NameIdentifier application to store the identifier. Check it out - ASP.NET MVC - set a custom IIdentity or IPrincipal option .

+2
source

Source: https://habr.com/ru/post/1437537/


All Articles