ASP.NET Core ValidationAttribute message language - asp.net-core

How can I globally overload error messages getting ,for example, from [Required] attribute? Probably, I should change CultureInfo, but I can't find any tutorials. Language still English as default. Thank you!

A first reference on globalization and localization of ASP.NET Core is https://docs.asp.net/en/latest/fundamentals/localization.html.
There you'll find information about how to translate data annotations and how to configure ASP.NET Core to select the appropriate language / CultureInfo for each request.
DataAnnotations error messages are localized with IStringLocalizer<T>.
Using the option ResourcesPath = "Resources", the error messages in
RegisterViewModel can be stored in either of the following paths:
Resources/ViewModels.Account.RegisterViewModel.fr.resx
Resources/ViewModels/Account/RegisterViewModel.fr.resx
For built-in error messages for identity models (like "This email is already taken.) or basic validation texts you have to do some more configuration. I have documented some work in ASP.Net Core localization.

You can try using ErrorMessageResourceName and ErrorMessageResourceType, using resource files to store messages.

Related

How to disable the model property validation of not-nullable properties?

I'm using FluentValidation in an ASP.NET Core 6 Web API project. This works fine for most cases, so:
Request body JSON syntax validation is done by ASP.NET Core.
Request object property validation is done by FluentValidation.
But there is one specific case that is problematic:
If the request type contains a not-nullable property (e.g. string instead of string?) and the request object contains a null value for it, validation is done by ASP.NET Core (but should be done by FluentValidation).
My current workaround is to annotate all that not-nullable properties with [ValidateNever] so that ASP.NET Core ignores them, but this is not nice.
Is there a way to disable ASP.NET Core model property validation of not-nullable properties?
Note: I can't disable ASP.NET Core validation completely because then it won't even return validation error results for JSON syntax errors.
try to set as below :
builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
The problem has been explained in this document:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.mvcoptions.suppressimplicitrequiredattributefornonnullablereferencetypes?view=aspnetcore-6.0

How to add logging to WCF?

I've used the solution from here for logging (and insert to DB) REST request successfully, now i have to do the same to WCF
[LogApiRequest]
public NadlanData GetNadlanData(decimal Id, KodFamilyEnum KodFamily)
{
ClsDalByTz objByTz = new ClsDalByTz();
return objByTz.getDataFromMF(Id, DateTime.Now.Year - 5, (decimal)KodFamily);
}
I've tried to do the same by adding [LogApiRequest] to the WCF function but it did not work.
How can i implement the same solution for WCF?
The custom attribute - LogApiRequest - derives from System.Web.Http.Filters.ActionFilterAttribute. Action filter attributes are documented here - https://www.tutorialsteacher.com/webapi/web-api-filters and here - https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs.
The reason your attribute works in your web api is because asp.net or asp.net core processing pipeline supports calling custom code defined in user defined code - you are plugging custom feature in the processing pipeline.
Know more about asp.net pipeline here - https://learn.microsoft.com/en-us/archive/msdn-magazine/2002/september/asp-net-request-processing-filtering-and-content-redirection
The reason it does not work with WCF is because that processing pipeline does not support customisation through HTTP filters.
WCF has its own way of doing logging. Check out these links - https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing and https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging
You will find yourself editing custom configuration files most of the time.
I cannot give you a short attribute name or configuration script because it depends on type of WCF endpoint you are implementing, their name etc. The tracing and message logging link above contains some samples. Copy paste those configurations but edit file path and interface names based on what you have got code. That should work.

Should I use IEmailSender?

I'm using AspNetCore.Identity at my project, so I write a EmailSender class that implements this interface.
Everything is working fine.
But this description about IEmailSender took my attention:
Microsoft.AspNetCore.Identity.UI.Services.IEmailSender
This API supports the ASP.NET Core Identity default UI infraestructure and is not intended to be used directly from your code. This API may change or be removed in future releases
If it isn't intended to be used directly in my code, what should I use?
My application also send emails in other parts, not only for Identity.
I don't think you need to use IEmailSender. In fact, based on my experience, to some degrees I think you shouldn't use it:
In .NET 5.0, IEmailSender is in the package ASP.NET Core Identity.UI, with the default implementation injected in DI that doesn't do anything. It's perfectly fine if you want to use the default UI provided by the framework. But if you don't like to use those default pages and just want to use the core of the Identity framework, including the whole package just to get IEmailSender interface seems overkill to me. Not to mention there is an annoying bug when using Identity UI at this moment.
It doesn't add any value. I would have been persuaded if the framework could automatically scan my concrete implementation and use that instead to send out emails. But that's not the case. You would have to inject your email sender through DI by services.AddSingleton<>() yourself and use it via constructor injection where you want to send emails.
IEmailSender.SendEmailAsync(string email, string subject, string htmlMessage) method is pretty basic. Most of the time you even would have to create your own razor library to generate the HTML message yourself. In my case (using SendGrid v9.22 with dynamic template), I would need to not only pass the HTML message, but also the template data (for setting the placeholder in my SendGrid template via msg.SetTemplateData()). The basic SendEmailAsync() just doesn't have extra parameters for me to send additional data when sending the email.
Conclusion:
If you see yourself that you won't switch to email provider for a project, you might as well just create a concrete email sender that fits you well, and inject that into DI directly.
If you see there might be a time when your project will switch email provider, having a basic and simple interface, like IEmailSender, makes sense.
You definitely should, as the IEmailSender is the best available option offered by the framework to send email messages, especially if you have to deal with ASP.NET Identity stuff (account confirmation, password recovery and so on).
However, in order to use it properly, you should implement it using one of the many third-party services (and their corresponding .NET NuGet packages), as suggested in this official post.
If you need further instruction to setup these email sender provider, you can take a look at these implementation guides that I wrote on my blog (DISCLAIMER: I'm not affiliated with any of them):
.NET Core General Purpose SMTP implementation using MailKit
.NET Core IEmailSender implementation using Twilio SendGrid API
.NET Core IEmailSender implementation using SendInBlue API
The fact that the API could get removed in the future shouldn't bother you at all, since all of these third-party packages have their own API: you'll be able to use them even without the IEmailSender interface (as a matter of fact, you already can).

ASP.NET Core 3.0 - Model Binding not inferred?

According to the documentation, complex types should automatically be handled as "FromBody" without the need to decorate the parameter with an attribute. For whatever reason it isn't working for me. What am I missing? Thanks.
ASP.NET Core 3, Content Type of the Header is "application/json".
From the Microsoft documentation
The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.
The complex types could automatically be handled as "FromBody" when you use the [ApiController] attribute on the controller .

What is the purpose of AddFormatterMappings() on Asp.net Core 2

I am evaluating the configuration of a Web API App with Asp.Net Core 2. To configure I know it is better for my project to use .AddMvcCore() rather then use AddMvc() since I don't need Razor as we can see here.
Now, I am not sure if I also need this .AddFormatterMappings(). So my question is what is it for?
You can see from the source code in the MVC GitHub repo that it adds a FormatFilter service into the DI setup. The summary for the FormatFilter class is as follows:
A filter that will use the format value in the route data or query
string to set the content type on an ObjectResult returned from an
action.