encrypt decrypt string in asp.net Core

March 22, 2019 0 comments
This article is all about Implementing Simple AES encryption decryption algorithm in Asp.net Core.

We can actually use the same code for .net framework 4.7.2 also.

Use using System.Security.Cryptography;
Just make sure the key which we use for encryption and decryption is same. In our case we are using following key (This key I have copied from some references I already have.)



private static string keyString = "E546C8DF278CD5931069B522E695D4F2";



For encryption use following function, I generally keep Helper functions as static function

public static string EncryptString(string text)
        {
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, 
encryptor, CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(text);
                        }

      var iv = aesAlg.IV;
      var decryptedContent = msEncrypt.ToArray();
      var result = new byte[iv.Length + decryptedContent.Length];
      Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
      Buffer.BlockCopy(decryptedContent, 0, result, iv.Length,
     decryptedContent.Length);

                        return Convert.ToBase64String(result);
                    }
                }
            }
        }

For decryption use following function


public static string DecryptString(string cipherText)
        {
            var fullCipher = Convert.FromBase64String(cipherText);

            var iv = new byte[16];
            var cipher = new byte[16];

            Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var decryptor = aesAlg.CreateDecryptor(key, iv))
                {
                    string result;
                    using (var msDecrypt = new MemoryStream(cipher))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt,
 decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                result = srDecrypt.ReadToEnd();
                            }
                        }
                    }

                    return result;
                }
            }
        }

How to Get client ip address in .net core 2.x

March 16, 2019 0 comments
To get client IP address in Asp.net core 2.x, you have to inject HttpContextAccessor 

Declare private variable in class


   private IHttpContextAccessor _accessor;


Initialize above private variable in default constructor and retrieve IP address as showed in following code


public class HomeController : Controller
    {
        private readonly IUserRepository userRepository;
        private IHttpContextAccessor _accessor;

        public HomeController(IUserRepository userRepository,
        IHttpContextAccessor accessor)
        {
            this.userRepository = userRepository;
            this._accessor = accessor;
        }
        public IActionResult Index()
        {
   ViewBag.IpAddress = 
_accessor.HttpContext.Connection.RemoteIpAddress.ToString();
   return View();
        }
    }



Make sure you initialize IHTTPContextAccessor in startup.cs


services.TryAddSingleton<ihttpcontextaccessor httpcontextaccessor="">();
</ihttpcontextaccessor>


If you don't register IHTTPContextAccessor .net core will give you following error

 InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate

.net core get host ip address

Get Client ip address in .net core 2.0

SqlException: Cannot open database "DATABASE" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\APPPOOLNAME'.

March 14, 2019 0 comments
While deploying web based and Mobile based Attendance system on IIS and MSSQL2017, I got following error.
  1. Project developed using Entity Framework Core and MVC .net Core 2.2
  2. To deploy web application in IIS, I published core 2.2 web application and put it under IIS.
  3. Assigned new APP Pool with with No Managed Code for .NET CLR Version.
I got following SQL related error

An unhandled exception occurred while processing the request.

SqlException: Cannot open database "DATABASE" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\apppoolname'.

System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, object providerInfo, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling, string accessToken)

To resolve this issue, simply create User named 'IIS APPPOOL\apppoolname in SQL

SqlException: Cannot open database "DATABASE" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\apppoolname'

After creating user, assign it to your respective database and give db permissions to that user.

This will resolve the issue.



Swapping to Development environment will display more detailed information about the error that occurred.

March 14, 2019 0 comments
While developing Employee Mobile based and Web based Attendance system in .net core 2.2.
  1. I published application using VS2017
  2. Then I put this application in IIS and assigned an Application Pool with No Managed Code for .NET CLR Version.
  3. When I was running my application on Chrome browser, I got following error.

Swapping to Development environment will display more detailed information about the error that occurred.
Error. An error occurred while processing your request. Development Mode Swapping to Development environment will display more detailed information about the error that occurred.
Development environment should not be enabled in deployed applications, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the ASPNETCORE_ENVIRONMENT environment variable to Development, and restarting the application.

To resolve this error and check actual error in details, open web.config file and add following code



<aspnetcore>
  <environmentvariables>
       <environmentvariable name="ASPNETCORE_ENVIRONMENT" value="Development">
   </environmentvariable></environmentvariables>
</aspnetcore>