}
@code {
[Parameter]
public string id { get; set; } = string.Empty;
private Role? role;
protected override async Task OnInitializedAsync()
{
if ( id is not null)
{
role = await GetRole(id);
}
else
{
role = new Role();
}
}
public async Task GetRole(string roleId)
{
var customAuthStateProvider = (CustomAuthorizationProvider)authenticationStateProvider;
var token = await customAuthStateProvider.GetTokenData();
if (!string.IsNullOrWhiteSpace(token.token))
{
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
try
{
var response = await _httpClient.GetAsync("/api/Account/GetRoleById/"+roleId);
if (response.IsSuccessStatusCode)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
Role role = JsonSerializer.Deserialize(jsonResponse, options) ?? new Role();
return role;
}
}
catch
{
return null;
}
};
return null;
}
private async Task UpsertRole()
{
if(role.Id is null)
{
await CreateRole();
}
else
{
await UpdateRole();
}
}
public async Task UpdateRole()
{
if (role == null)
{
toastService.ShowError("Role no está definido.");
return;
}
var requestContent = new StringContent(JsonSerializer.Serialize(role), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync("/api/Account/UpdateRole/" + role.Id, requestContent);
if (response.IsSuccessStatusCode)
{
toastService.ShowSuccess("El registro fue actualizado correctamente!");
Navigation.NavigateTo("/roles"); // Redirige a la página de roles después de la actualización
}
else
{
// Manejar errores de actualización
var errorResponse = await response.Content.ReadAsStringAsync();
toastService.ShowError(errorResponse);
}
}
public async Task CreateRole()
{
var newConcurrencyStamp = Guid.NewGuid().ToString();
var requestContent = new StringContent(JsonSerializer.Serialize(role), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/Account/CreateRole/", requestContent);
var errorResponse = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
toastService.ShowSuccess(errorResponse);
Navigation.NavigateTo("/roles"); // Redirige a la página de roles después de la actualización
}
else
{
toastService.ShowError(errorResponse);
}
}
public void Cancel()
{
Navigation.NavigateTo("/roles");
}
public class Role
{
public string? Id { get; set; }
public string? Name { get; set; }
public string? NormalizedName { get; set; }
public string? ConcurrencyStamp { get; set; }
}
}