hunterlan
hunterlan
CC#
Created by hunterlan on 8/27/2024 in #help
Blazor Static SSR - redirect after form submission
I woudl like to redirect user after successful login. However, after NavigationManager.NavigateTo, it throws an exception. I tried to find any useful information, but I found nothing. Here's my HTML form:
<EditForm Enhance="true" Model="LoginEmployee" OnSubmit="HandleSubmit" FormName="Login">
<div class="login">
@*img logo?*@
<h2 style="text-align: center; font-family: NunitoSans-Regular, serif">Login</h2>
<div>
<label class="usernameLabel">
Username:
<InputText style="height: 27px; margin-top: 8px;" type="text" @bind-Value="LoginEmployee!.Login"></InputText>
</label>
</div>
<div>
<label class="passwordLabel">
Password:
<InputText style="height: 27px; margin-top: 8px;" type="password" @bind-Value="LoginEmployee!.Password"></InputText>
</label>
</div>
<div class="buttons">
<button class="loginButton" type="submit">Login</button>
</div>
</div>
</EditForm>
<EditForm Enhance="true" Model="LoginEmployee" OnSubmit="HandleSubmit" FormName="Login">
<div class="login">
@*img logo?*@
<h2 style="text-align: center; font-family: NunitoSans-Regular, serif">Login</h2>
<div>
<label class="usernameLabel">
Username:
<InputText style="height: 27px; margin-top: 8px;" type="text" @bind-Value="LoginEmployee!.Login"></InputText>
</label>
</div>
<div>
<label class="passwordLabel">
Password:
<InputText style="height: 27px; margin-top: 8px;" type="password" @bind-Value="LoginEmployee!.Password"></InputText>
</label>
</div>
<div class="buttons">
<button class="loginButton" type="submit">Login</button>
</div>
</div>
</EditForm>
C# code:
public partial class Login : ComponentBase
{
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
[SupplyParameterFromForm]
private LoginEmployeeCommand? LoginEmployee { get; set; } = new();
private string ErrorMessage { get; set; } = string.Empty;

/// <inheritdoc />
protected override void OnInitialized()
{
LoginEmployee ??= new LoginEmployeeCommand();
var isAuthenticated = HttpContext!.User.Identity!.IsAuthenticated;
ErrorMessage = string.Empty;
if (isAuthenticated)
{
NavigationManager.NavigateTo("/", forceLoad: true);
}
}

private async Task HandleSubmit()
{
if (string.IsNullOrWhiteSpace(LoginEmployee.Login) || string.IsNullOrWhiteSpace(LoginEmployee.Password))
{
ErrorMessage = "Username and password are required.";
}
else
{
try
{
var user = await Mediator.Send(LoginEmployee);
await CookieService.SignInAsync(user);
}
catch (NotFoundException)
{
Logger.LogWarning("User not found error");
ErrorMessage = "Invalid login credentials";
}
catch (InvalidOperationException)
{
Logger.LogWarning($"Login failed: User: [{LoginEmployee.Login}]");
ErrorMessage = "Invalid login credentials";
}
catch (Exception ex)
{
Logger.LogError(ex, "Login failure");
ErrorMessage = "Something went wrong";
}
}
}
}
public partial class Login : ComponentBase
{
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
[SupplyParameterFromForm]
private LoginEmployeeCommand? LoginEmployee { get; set; } = new();
private string ErrorMessage { get; set; } = string.Empty;

/// <inheritdoc />
protected override void OnInitialized()
{
LoginEmployee ??= new LoginEmployeeCommand();
var isAuthenticated = HttpContext!.User.Identity!.IsAuthenticated;
ErrorMessage = string.Empty;
if (isAuthenticated)
{
NavigationManager.NavigateTo("/", forceLoad: true);
}
}

private async Task HandleSubmit()
{
if (string.IsNullOrWhiteSpace(LoginEmployee.Login) || string.IsNullOrWhiteSpace(LoginEmployee.Password))
{
ErrorMessage = "Username and password are required.";
}
else
{
try
{
var user = await Mediator.Send(LoginEmployee);
await CookieService.SignInAsync(user);
}
catch (NotFoundException)
{
Logger.LogWarning("User not found error");
ErrorMessage = "Invalid login credentials";
}
catch (InvalidOperationException)
{
Logger.LogWarning($"Login failed: User: [{LoginEmployee.Login}]");
ErrorMessage = "Invalid login credentials";
}
catch (Exception ex)
{
Logger.LogError(ex, "Login failure");
ErrorMessage = "Something went wrong";
}
}
}
}
8 replies
CC#
Created by hunterlan on 3/18/2024 in #help
Root - level cascading value and parameter
According to official documentation(https://learn.microsoft.com/en-us/aspnet/core/blazor/components/cascading-values-and-parameters?view=aspnetcore-8.0), I can create a cascading parameter like that: builder.Services.AddCascadingValue(sp => new CascadingValueSource<UserState>(new UserState(), isFixed: false)); And then use it like that: [CascadingParameter] public UserState UserState { get; set; } And our variable UserState shouldn't be null, right? I have a Blazor Web App project (InteractiveAuto) and unfortunately, UserState for me is null. I called AddCascadingValue to both projects and it's still null. I don't understand what I am doing wrong.
1 replies
CC#
Created by hunterlan on 1/10/2024 in #help
Unable to set property 'onsubmit' on object of type
Hi everyone! I created a simple login page but it throws me an exception:
InvalidOperationException: Unable to set property 'onsubmit' on object of type 'Microsoft.AspNetCore.Components.Forms.EditForm'. The error was: Unable to cast object of type 'Microsoft.AspNetCore.Components.EventCallback`1[System.EventArgs]' to type 'Microsoft.AspNetCore.Components.EventCallback`1[Microsoft.AspNetCore.Components.Forms.EditContext]'.
InvalidOperationException: Unable to set property 'onsubmit' on object of type 'Microsoft.AspNetCore.Components.Forms.EditForm'. The error was: Unable to cast object of type 'Microsoft.AspNetCore.Components.EventCallback`1[System.EventArgs]' to type 'Microsoft.AspNetCore.Components.EventCallback`1[Microsoft.AspNetCore.Components.Forms.EditContext]'.
Here's my blazor page:
@page "/Login"
@using System.Text.Json
@using System.Net
@using Novel.Blazor.Models
@inject HttpClient HttpClient
@inject ProtectedSessionStorage ProtectedSessionStore
<h3>Login</h3>
@rendermode InteractiveServer

<div>
<EditForm method="post" Model="@LoginUser" @onsubmit="@Submit">
<InputText type="email" @bind-Value="LoginUser.Email"></InputText>
<InputText type="password" @bind-Value="LoginUser.Password"></InputText>
<button type="submit">Login</button>
</EditForm>
</div>

@code {
[SupplyParameterFromForm]
private LoginUser? LoginUser { get; set; }

protected override void OnInitialized() => LoginUser ??= new LoginUser();
[Inject] ModalService ModalService { get; set; } = default!;
private async Task Submit()
{
var serialized = JsonSerializer.Serialize(LoginUser);

var result = await HttpClient.PostAsJsonAsync($"api/User", serialized).ConfigureAwait(true);
if (result.IsSuccessStatusCode)
{
await using var responseStream = await result.Content.ReadAsStreamAsync();
var token = await JsonSerializer.DeserializeAsync
<TokenDto>(responseStream);
await ProtectedSessionStore.SetAsync("token", token!.Token);
}
else
{
if (result.StatusCode == HttpStatusCode.Unauthorized)
{
await ShowError("Email or/and password are incorrect!");
}
else
{
await ShowError("Something went wrong");
}
}
}

private async Task ShowError(string message)
{
var modalOption = new ModalOption
{
Title = "Modal title",
Message = message,
Type = ModalType.Danger,
Size = ModalSize.Regular
};

await ModalService.ShowAsync(modalOption);
}

}
@page "/Login"
@using System.Text.Json
@using System.Net
@using Novel.Blazor.Models
@inject HttpClient HttpClient
@inject ProtectedSessionStorage ProtectedSessionStore
<h3>Login</h3>
@rendermode InteractiveServer

<div>
<EditForm method="post" Model="@LoginUser" @onsubmit="@Submit">
<InputText type="email" @bind-Value="LoginUser.Email"></InputText>
<InputText type="password" @bind-Value="LoginUser.Password"></InputText>
<button type="submit">Login</button>
</EditForm>
</div>

@code {
[SupplyParameterFromForm]
private LoginUser? LoginUser { get; set; }

protected override void OnInitialized() => LoginUser ??= new LoginUser();
[Inject] ModalService ModalService { get; set; } = default!;
private async Task Submit()
{
var serialized = JsonSerializer.Serialize(LoginUser);

var result = await HttpClient.PostAsJsonAsync($"api/User", serialized).ConfigureAwait(true);
if (result.IsSuccessStatusCode)
{
await using var responseStream = await result.Content.ReadAsStreamAsync();
var token = await JsonSerializer.DeserializeAsync
<TokenDto>(responseStream);
await ProtectedSessionStore.SetAsync("token", token!.Token);
}
else
{
if (result.StatusCode == HttpStatusCode.Unauthorized)
{
await ShowError("Email or/and password are incorrect!");
}
else
{
await ShowError("Something went wrong");
}
}
}

private async Task ShowError(string message)
{
var modalOption = new ModalOption
{
Title = "Modal title",
Message = message,
Type = ModalType.Danger,
Size = ModalSize.Regular
};

await ModalService.ShowAsync(modalOption);
}

}
Here's LoginUser class:
public class LoginUser
{
public string Email { get; set; }

public string Password { get; set; }
};
public class LoginUser
{
public string Email { get; set; }

public string Password { get; set; }
};
What am I doing wrong?
6 replies
CC#
Created by hunterlan on 12/12/2023 in #help
xUnit: Can't assert exceptions
Hello, there! I want to compare exception types, but I'm getting error. Here's my code:
var exception = await Assert.ThrowsAsync<ArgumentException>(() => _endpoint.GetReport("1.1.1.1", null));
Assert.Equal("Api key shouldn't be empty.", exception.Message);
var exception = await Assert.ThrowsAsync<ArgumentException>(() => _endpoint.GetReport("1.1.1.1", null));
Assert.Equal("Api key shouldn't be empty.", exception.Message);
Here's an error:
System.ArgumentException: Api key shouldn't be empty.

System.ArgumentException
Api key shouldn't be empty.
System.ArgumentException: Api key shouldn't be empty.

System.ArgumentException
Api key shouldn't be empty.
Here's part of code which I want to test:
protected string ApiKey
{
get => _apiKey;
init
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Api key shouldn't be empty.");
}

_apiKey = value;
}
}
protected string ApiKey
{
get => _apiKey;
init
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Api key shouldn't be empty.");
}

_apiKey = value;
}
}
6 replies
CC#
Created by hunterlan on 12/6/2023 in #help
No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
Hello, there! I added JWT Authentication to my ASP.NET Core Web API project by this code snipper:
builder.Services.AddAuthentication(a =>
{
a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer("jwt", o =>
{
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = config["Jwt:Issuer"],
ValidAudience = config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]!)),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
builder.Services.AddAuthentication(a =>
{
a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
a.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer("jwt", o =>
{
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = config["Jwt:Issuer"],
ValidAudience = config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]!)),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true
};
});
Then, when I'm requesting any endpoint that requires authorization, asp.net core throws an exception:
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<<HandleAsync>g__Handle|0>d.MoveNext()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<<HandleAsync>g__Handle|0>d.MoveNext()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
What am I doing wrong?
4 replies
CC#
Created by hunterlan on 7/19/2023 in #help
❔ Blazor Server: "This localhost page can't be found"
5 replies
CC#
Created by hunterlan on 7/9/2023 in #help
❔ VS 2022 Hot Reload disabled
67 replies
CC#
Created by hunterlan on 12/19/2022 in #help
❔ Problem with running console application on Linux
7 replies
CC#
Created by hunterlan on 10/7/2022 in #help
What's better to get in request?
I have a an element, which has count and type of measurement. In request, is better to get name of measurement or to get id of it?
8 replies