FluentValidation in Blazor: how to pass Dependency into custom validator - fluentvalidation

I am using FluentValidation in Blazor WebAssembly Project.
I need to pass HttpClient into FluentValidation to do Email check ?
How do i go about it?
<EditForm Model="_editprofileModel" OnValidSubmit="UpdateProfile">
<FluentValidator TValidator="EditProfileValidator" />
<ValidationSummary />
...........
</EditForm>
I want to do something like this, but it give compiler Error "the name _Http does not exist in the current context
<FluentValidator TValidator="EditProfileValidator(_Http)" />

Related

How do I display a delete confirmation dialog before deleting a row in a DevExtreme DataGrid on a Razor page?

I am using DevExtreme and razor pages in a Asp.NetCore web application.
I would like to inject client side delete confirmation dialog when deleting a row.
Currently I'm using an asp-action on the controller to make the call to do the delete.
I'm not sure how/where to do this in client side (cshtml file).
I assume that I'd be somehow using javascript/jquery for this?
Are there existign 3rd party open source libraries that I should use for client side dialogs/message boxes?
DevExtreme DataGrid definition in cshtml file.
#(Html.DevExtreme().DataGrid<Customer>()
.DataSource(Model)
.Columns(columns => {
columns.AddFor(m => m.CustomerName);
columns.AddFor(m => m.CustomerId).CellTemplate(
<form asp-action="DeleteCustomer" method="post">
<input type="hidden" value="<%- data.CustomerId %>" name="CustomerId" />
<input type="image" src="/icon/close.png" />
</form>
</text>).Caption("");
});
Server side control action code:
[HttpPost]
public async Task<IActionResult> DeleteCustomer(Guid customerId)
{
// Call WebApi Service to delete row
return RedirectToAction("Index");
}
I believe the datagrid has a built-in function for confirming the delete action on the client side. Might not be exactly what you were looking for but it could be a good start.
Here is the link to the demo page: https://demos.devexpress.com/ASPNetCore/Demo/DataGrid/RowEditingAndEditingEvents/

Blazor hosted - authorize immediately before displaying application

Can anybody give me a helping push to get my hosted Blazor application (Client, Server and Shared) to request a login immediately, before the application is initially shown. I want the experience that a user must log in before accessing the application at all.
My starting point is the Blazor Webassembly (hosted) template with Api Authorization (Individual User Accounts)
Using the Authorize attribute on either server-side actions or a client-side Razor page will not initiate the authentication flow before the specific action/page with the Authorize attribute is being requested by the user. How would I go about having the authorization flow kicked off as the first thing, before the application is even displayed for the first time?
I am sure this is possible and even trivial for somebody more savvy than me. Can anybody give me a shove in the right direction, please?
I created a control RedirectToLogin.razor
#inject NavigationManager Navigation
#code {
protected override void OnInitialized()
{
String thisPage = Navigation.Uri.Replace(Navigation.BaseUri, "~/");
Navigation.NavigateTo($"Identity/Account/Login?returnUrl={thisPage}");
base.OnInitialized();
}
}
And then inserted it into the mainlayout.razor
<div class="container-fluid">
<AuthorizeView>
<Authorized>
<NavigationLogger />
<ContextMenuMouseClick>
<MenuTopBar />
<NavMenu />
<SubPageContainer>
#Body
</SubPageContainer>
</ContextMenuMouseClick>
</Authorized>
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeView>
</div>
So when the layout is loaded and it is in the NotAuthorized state it will redirect to the login page and after authorising will return to the page it was trying to access.
Hope this helps.
The Blazor Client is bootstrapped from a static index.html in the wwwroot. In the Server project this is mapped to an Endpoint in the Startup.cs, basically a catch-all to all endpoints not taken by your Razor Pages or Controllers:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
For your scenario:
Create a new layout in Server, say _LayoutBlazor.cshtml
Re-create the contents of the index.html from the Client. Note that the _framework files from the Client are copied to the Server wwwroot upon build:
:
<app>Loading...</app>
<script src="#Href("~/_framework/blazor.webassembly.js")"></script>
Create a new Razor page and put the "Authorize" tag on it and use the _LayoutBlazor.
Remove the endpoints.MapFallbackToFile("index.html"); from Startup.cs
Mark Gould has created a proof of concept here: RazorBlazor

Disable request verification token in ASP.NET Core

ASP.NET Core MVC seems to inject a request verification token in all of my forms:
<form class="actions" method="post">
<input type="submit" class="btn btn-primary" value="Yes">
<a class="btn btn-secondary" href="/some/url">No</a>
<input name="__RequestVerificationToken" type="hidden" value="...">
</form>
I'm handling CSRF in Ajax and don't want this extra input element in all of my forms. Any way to disable it?
The element is added even without a call to AddAntiforgery in Startup.cs. I'm running on ASP.NET Core 3.1.
Antiforgery middleware is added to the Dependency injection container when one of the following APIs is called in Startup.ConfigureServices:
AddMvc
MapRazorPages
MapControllerRoute
MapBlazorHub
Details please check this document
To disable it, try below IgnoreAntiforgeryToken attribute
[Authorize]
[AutoValidateAntiforgeryToken]
public class ManageController : Controller
{
[HttpPost]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> DoSomethingSafe(SomeViewModel model)
{
// no antiforgery token required
}
}
Details can be found here
The token is appended by the Form Tag Helper. If you don't need the other features of the Tag Helper, it can be removed using #removeTagHelper (in view or globally by adding to _ViewImports.cshtml):
#removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
See ASP.NET Core documentation for further details/options.
Just idea I would make reference to that [IgnoreAntiforgeryToken] can be used to disable the global [AutoValidateAntiForgeryToken] attribute on certain actions if needed.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new IgnoreAntiforgeryTokenAttribute());
});
}
}

NavigationError on NavigateTo

I'm trying out Blazor ServerSide and created a Component to Redirect To the Login Page when a user is not logged in.
#inject Microsoft.AspNetCore.Components.NavigationManager NavigationManager;
#code {
/// <inheritdoc />
protected override Task OnInitializedAsync()
{
NavigationManager.NavigateTo("Login");
return Task.CompletedTask;
}
}
But always when "NavigateTo" is called the following exception is thrown:
"Microsoft.AspNetCore.Components.NavigationException: Exception of type 'Microsoft.AspNetCore.Components.NavigationException' was thrown.
at Microsoft.AspNetCore.Components.Server.Circuits.RemoteNavigationManager.NavigateToCore(String uri, Boolean forceLoad)
at Microsoft.AspNetCore.Components.NavigationManager.NavigateTo(String uri, Boolean forceLoad)
at ApplySupportTool.Blazor.Pages.RedirectToLogin.OnInitializedAsync() in C:\\Users\\padruttn\\Documents\\git\\ApplySupportTool\\src\\ApplySupportTool.Blazor\\Pages\\RedirectToLogin.razor:line 8"
Interesstingly the navigation is made despite the exception.
I also tried to call it with the path "/login" but the same behaviour here.
There is an open issue on github for this problem. See also the preceeding issue where a possible workaround is mentioned: putting the NavigateTo method into OnAfterRender instead of OnInitialized.
I needed to put this into OnInitialized rather than OnAfterRender, so had to go with the render-mode="Server" method, though apparently this isn't recommended.
It also states in the GitHub issue that this only happens in debug, not release, so a middle ground option is to change _Host.cshtml to contain:
<environment include="Staging,Production">
<component render-mode="ServerPrerendered" type="typeof(App)" />
</environment>
<environment include="Development">
<component render-mode="Server" type="typeof(App)" />
</environment>
Note that the following may be considered a workaround:
You may also change your method to the following including the "async" keyword to its signature, there is going to be a complaint about not using await, but in exchange you are not going to need a return value. Since it doesn't have an 'await' the effect is kinda the same as the synchronous version, but without the exception being thrown.
protected override async Task OnInitializedAsync()
{
NavigationManager.NavigateTo("Login");
}
Here is an example where i am using a RedirectToLogin.razor component in my routing
#inject NavigationManager NavigationManager
#code{
protected override async Task OnInitializedAsync()
{
var returnUrl = "~/" + NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
NavigationManager.NavigateTo($"Identity/Account/Login?returnUrl={returnUrl}", forceLoad:false);
}
}
And in my App.razor
<Found Context="routeData">
<AuthorizeRouteView RouteData="#routeData" DefaultLayout="#typeof(MainLayout)">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeRouteView>
</Found>
Old post, but - if you are running a Blazor Server app, this behavior only happens if render-mode is "ServerPrerendered". Disabling Pre-rendering by changing the mode to "Server" makes the exception not be thrown in the first place:
<app>
<component type="typeof(App)" render-mode="Server" />
</app>
I've searched current Blazor Documentation and change notes, and haven't found any mention of this, so just in case it helps somebody else...
I ran into the same problem and filed issue #28355. The official answer is, that it is save to ignore the exception when NaviagteTo is placed in OnInitialized. Here is the answer from javiercn:
Yes, it is completely safe to ignore it. The debugger stops because it is configured to do so, but in this case the exception is always handled. You can turn-off breaking on this exception if it's caught on the debugger settings.
Issue #13582 deals with how to prevent the debugger from stopping at this exception.
use OnInitializedAsync replace OnInitialized
protected override async Task OnInitializedAsync()
{
nav.NavigateTo("/login", true);
await base.OnInitializedAsync();
}
I had this when I tried to call the navigateto from another thread. render-mode = "Server" - solved the problem
In .NET 5.0, in the _host.cshtml file. Past the following #(await Html.RenderComponentAsync(RenderMode.Server)) in the line after the "blazor_error_ui" section.

Inconsistent Asp.net MVC4 (Razor 2.0) Rendering if Write in html attribute

In cshtml view (Razor 2.0) I Have got code:
<input type="text" value="#if (true) { Write("simpletext"); } " />
In Result html generated by Razor 2.0 (MVC4) I have got:
<input type="text"simpletext value=" " />
In Razor 1.0 (MVC3) code is correct:
<input type="text" value="simpletext" />
It's seems like render processor wait quotation close, then add attribute to result stream.
How I can configure razor 2.0 to work as razor 1.0 in this case?
Thank you.
Try not using the Write function, but using the string directly in a ternary if
<input type="text" value="#(true ? "simpletext" : "")" />
Why dont you use HTML Helpers provided by Razor? I think this will help out by using HTML Helpers
#if (true) { #Html.Encode("SimpleText")}