Friday, August 23, 2019

Validate AntiForgeryToken in Dot Net CORE MVC

To validate authentication based on AntiForgeryToken in dot net CORE MVC application, perform below steps

(1) Add below line of code to Startup.cs --> ConfigureServices
services.AddMvc(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
services.AddAntiforgery(options => options.HeaderName = "Name of token in header");

(2) CSHTML: Put below line of code to view/page where we want to validate token
@Html.AntiForgeryToken()

(3) Controller Method: Put below attribute as an attribute to the method for which we want to validate token
[ValidateAntiForgeryToken]

(4) Token: once above steps get done, from your js/cshtml find token with below line of code
var token = $('[name= "__RequestVerificationToken"]').val();

(5) For ajax calls:For ajax calls put below header line of code
headers: {
                'Name of token in header': token from step-(4)
            },

Here is one reference link that I found good for me
Enable Antiforgery Token with ASP.NET Core and JQuery



Wednesday, August 21, 2019

Logging with NLog

Here are some links and tips & tricks for nLog nuget extension. Find how to work with it and additionally there are some tips to make some more change in its configuration to achieve specific needs.

ASP.NET Core Web API – Logging With NLog

Introduction to NLog

NLog: Rules and filters

- To check with configuration of file
Configuration file

- To working from code base
Configure from code

Things your Dad never told you about NLog

- Tips & Tricks
Turn off Logging during Release from Nlog.config

How to turn ON and OFF logging for specific levels in NLog

how to disable the particular log, dynamically in Nlog using C#?

- Additionally
(1) To log only Info message

<logger name="*" minlevel="Info" maxlevel="Info" writeTo="logfile" />

or

<logger levels="Info" name="*" writeTo="logfile"/>

(2) To log multiple message, below change will log messages for Error and Info and that way we can add other too
<logger levels="Info,Error" name="*" writeTo="logfile"/>

(3) To disable logging set enable to false
<logger name="*" minlevel="Debug" writeTo="logfile"  enabled="false" /
>