Creating Add Role Endpoint
In this lesson, we're going to create an addRole endpoint
Creating Add Role endpoint#
As we discussed in the last lesson, let's create an endpoint for adding role. For this, we can go to UsersController and create a new endpoint. This will be Authorized endpoint and will be a post request with name, addRole. Let's write the method now; public async task of type actionResult with name add role. Inside, we need a user which is equal to userManager.findByNameAsync and inside, we can pass User.Identity.Name; after this, we can use userManager.AddToRoleAsync and pass user and the role Instructor. Finally, let's return Ok.
API/Controllers/UsersController.cs
[Authorize]
[HttpPost("addRole")]
public async Task<ActionResult> AddRole()
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
await _userManager.AddToRoleAsync(user, "Instructor");
return Ok();
}
Now let's go to the agent file and add this endpoint inside Users. Let's call this addRole and this will be a post request so let's type the url, users/addRole
, and pass the empty body.
client/src/actions/agent.ts
//
const Users = {
login: (values: Login) => requests.post < User > ('users/login', values),
register: (values: Register) =>
requests.post < User > ('users/register', values),
addCourse: () => requests.post('users/purchaseCourses', {}),
currentUser: () => requests.get < User > 'users/currentUser',
addRole: () => requests.post('users/addRole', {}),
};
//
client/src/redux/slice/userSlice.ts
This page is a preview of The newline Guide to Fullstack ASP.NET Core and React