text stringlengths 0 13.4k |
|---|
to get the current user in the Index action: |
public async Task<IActionResult> Index() |
79 |
Using identity in the application |
{ |
var currentUser = await _userManager.GetUserAsync(User); |
if (currentUser == null) return Challenge(); |
var items = await _todoItemService |
.GetIncompleteItemsAsync(currentUser); |
var model = new TodoViewModel() |
{ |
Items = items |
}; |
return View(model); |
} |
The new code at the top of the action method uses the UserManager to |
look up the current user from the User property available in the action: |
var currentUser = await _userManager.GetUserAsync(User); |
If there is a logged-in user, the User property contains a lightweight |
object with some (but not all) of the user's information. The UserManager |
uses this to look up the full user details in the database via the |
GetUserAsync() method. |
The value of currentUser should never be null, because the |
[Authorize] attribute is present on the controller. However, it's a good |
idea to do a sanity check, just in case. You can use the Challenge() |
method to force the user to log in again if their information is missing: |
if (currentUser == null) return Challenge(); |
Since you're now passing an ApplicationUser parameter to |
GetIncompleteItemsAsync() , you'll need to update the ITodoItemService |
interface: |
Services/ITodoItemService.cs |
80 |
Using identity in the application |
public interface ITodoItemService |
{ |
Task<TodoItem[]> GetIncompleteItemsAsync( |
ApplicationUser user); |
// ... |
} |
Since you changed the ITodoItemService interface, you also need to |
update the signature of the GetIncompleteItemsAsync() method in the |
TodoItemService : |
Services/TodoItemService |
public async Task<TodoItem[]> GetIncompleteItemsAsync( |
ApplicationUser user) |
The next step is to update the database query and add a filter to show |
only the items created by the current user. Before you can do that, you |
need to add a new property to the database. |
Update the database |
You'll need to add a new property to the TodoItem entity model so each |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.