Access to XMLHttpRequest from origin has been blocked by CORS policy…

I did a Web API deployment in Azure Web API service. I was able to access the URL in browser and Postman. I started getting following error when I try to integrate in ASP.NET Web App in my local development environment;

Access to XMLHttpRequest at ‘https://xyz-dev.azurewebsites.net/api/Authentication/GetTestUser?name=testuser’ from origin ‘http://localhost:17686’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

jquery.js:9172          GET https://xyz-dev.azurewebsites.net/api/Authentication/GetTestUser?name=testuser net::ERR_FAILED

To solve the problem, I did this;

Here is server-side (Web API) code;

Add following to Web API ConfigureServices method;

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(op =>
    {
       op.AddPolicy("AllOrigin", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    });
}

Add following to Web API Configure method;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
      //-------use cords
      app.UseCors("AllOrigin");
}

Here is client-side AJAX call.

<input type="button" id="btnWebApiCall" name=" btnWebApiCall" value="Test CORS" class=" btn btn-primary btn-lg justify-content-center" />

@section Scripts
    {

    <script>

        $(document).ready(function () {

            $("#btnAuthenticateSSO").click(function (e) {
                e.preventDefault();
                $.ajax({
                    type: "GET",
                    url: "https://xyzapi-dev.azurewebsites.net/api/Authentication/GetTestUser?name=testuser",
                    contentType: "application/json; charset=utf-8",
                    //crossDomain: true,
                    dataType: "json",
                    success: function (data, status, xhr) {
                        alert(JSON.stringify(data));
                        console.log(data);
                    }, //End of AJAX Success function
                    error: function (xhr, status, error) {
                        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText);
                    } //End of AJAX error function

                });
            });

        });

    </script>

}

The pain is gone.

If interested in learning more about this, read below;

Researched and figured out that browser sends two requests to the server. Tiny request and actual request.

The browser sends a tiny request called a preflight request before the actual request. It includes details such as the HTTP method used and whether any custom HTTP headers are present. The preflight allows the server to see how the actual request would appear before it is sent. The server will then tell the browser whether or not to submit the request, or whether to return an error to the client instead.

See below for problem header without CORS and with CORS in web API;

Headers without CORS implementation in Web API (Problem);

Headers with CORS implementation in Web API (Problem solved);

A simple Get request make these two requests;

Resources

https://medium.com/easyread/enabling-cors-in-asp-net-web-api-4be930f97a5c

https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core

How .NET and SQL Server Handle Dates and Times

.NET and SQL Server have always come up short when it comes to handling date and time data. To be fair, most other languages and databases do as well. Although there have always been ways to cover the inadequacies, the work-arounds have always felt clumsy to me. We deal with them so often in our daily lives to the point that they seem rather simple and intuitive to us, yet dates and times are complicated concepts. Initially, both .NET and SQL Server set out to handle some of the most complicated aspects for us, each with its own DateTime data type.

Read more Here.

https://codemag.com/Article/2203041/.NET-6-Date-and-Time?utm_source=Knowbility3.9.2022&utm_medium=newsletter&utm_campaign=sm-articles

ASP.NET Core Middleware Configuration settings access

How do we access the configuration settings in the Middleware component in ASP.NET Core applications?

As we know middleware is a component that is used in the application pipeline to handle requests and responses which can help perform pre and post-operation within the request and response API pipeline.

We will be using two approaches, one with simple configuration and second with IOptions pattern. You can read more about it here;

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-6.0

Create ASP.NET Core API application based on .NET Core 3.1. We will be using this configuration;

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "GlobalConfigurationSettings": {
    "LowerEnvironment": "true",
    "CustomerConfig": {
      "CustomerKeyurl": "http://customer/key",
      "CustomerdetailsUrl": "http://customer/id",
      "Agency": {
        "AgencyID": "subvalue1_from_json",
        "AccountKey": 200
      }
    },
    "AllowedHosts": "*"
  }
}

This is a generic custom middleware;

public class CustomMiddleware
{
   private readonly RequestDelegate _next;

   public CustomMiddleware(RequestDelegate next)
   {
       _next = next;
   }
 
   public async Task InvokeAsync(HttpContext httpContext)
   {
       try
       {
           await _next(httpContext);
       }
       catch (Exception ex)
       {
           throw ex;
           //_logger.LogError($"Something went wrong: {ex.Message}");
       }
   }
}

Approach 1- Using IConfiguration to load the Config settings in Middleware

This approach does not require any custom interface. When CreateDefaultBuilder runs, it load application configuration by default from appsettings.json. This is available to any component in the application.

We are going to inject RequestDelegete and IConfiguration from the constructor in middleware;

public class MiddlewareWithIConfiguration
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configurationSettings;

        public MiddlewareWithIConfiguration(RequestDelegate next, IConfiguration optionsSettings)
        {
            _next = next;
            _configurationSettings = optionsSettings;
        }

Implement InvokeAsync (assuming we need asynchronous middleware behavior) method.

public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                var customerKeyUrl = _configurationSettings["GlobalConfigurationSettings:CustomerConfig:CustomerKeyurl"];
                Console.WriteLine($"Middleware using IConfiguration {customerKeyUrl}");
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                throw ex;
                //_logger.LogError($"Something went wrong: {ex.Message}");
            }
        }

Add this line to Startup.cs file;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

            app.UseMiddleware<MiddlewareWithIConfiguration>();
}

Approach 2 – Using IOption to load the Config settings in Middleware

We need to add and configure IOptions in Startup.cs file;

public void ConfigureServices(IServiceCollection services)
        {
            //Add functionality to inject IOptions<T>
            services.AddOptions();
            services.Configure<GlobalConfigurationSettings>(Configuration.GetSection("GlobalConfigurationSettings"));
}

We need a custom class to load configuration settings;

    public class GlobalConfigurationSettings
    {
        public string LowerEnvironment { get; set; }
        public CustomerConfig CustomerConfig { get; set; }
    }

    public class CustomerConfig
    {
        public string CustomerKeyurl { get; set; }
        public string CustomerdetailsUrl { get; set; }
        public Agency Agency { get; set; }
    }

Finally, we will be injecting RequestDelegete and IOptions from the constructor in middleware;

public class MiddlewareWithIOptions
    {
        private readonly RequestDelegate _next;
        private readonly GlobalConfigurationSettings _configurationSettings;

        public MiddlewareWithIOptions(RequestDelegate next, IOptions<GlobalConfigurationSettings> optionsSettings)
        {
            _next = next;
            _configurationSettings = optionsSettings.Value;
        }

And InvokeAsync method;

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                var lowerEnvironment = _configurationSettings.LowerEnvironment;
                var customerKeyUrl = _configurationSettings.CustomerConfig.CustomerKeyurl;
                Console.WriteLine($"Middleware using IOptions {lowerEnvironment} - {customerKeyUrl}");
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                throw ex;
                //_logger.LogError($"Something went wrong: {ex.Message}");
            }
        }

Add this line to Startup.cs file;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

            app.UseMiddleware<MiddlewareWithIOptions>();
}

If we want to restrict URL segment, we can write InvokeMethods like this;

       public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/swagger")
                && !context.User.Identity.IsAuthenticated)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return;
            }

            await _next.Invoke(context);
        }

For an example in controllers, refer to this article;

Resources

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

Return multiple values to a method caller

This is a code sample for returning multiple values from a c# method. For example, imagine a method that accepts multiple parameters and return two parameters;

So far the best method that I have found is this;

public Tuple<int, int> GetMultipleValue()
{
     return Tuple.Create(1,2);
}

This works in .NET 4 and up. Tuples with two values have Item1 and Item2 as properties.

Here is a list of different methods;

1. ref / out parameters

using ref:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add = 0;
    int multiply = 0;
    Add_Multiply(a, b, ref add, ref multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
    add = a + b;
    multiply = a * b;
}

using out:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add;
    int multiply;
    Add_Multiply(a, b, out add, out multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
    add = a + b;
    multiply = a * b;
}

2. struct / class

struct Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

using class:

class Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

3. Tuple

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.Item1);
    Console.WriteLine(result.Item2);
}

private static Tuple<int, int> Add_Multiply(int a, int b)
{
    var tuple = new Tuple<int, int>(a + b, a * b);
    return tuple;
}

C# 7 Tuples

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    (int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
    Console.WriteLine(a_plus_b);
    Console.WriteLine(a_mult_b);
}

private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
    return(a + b, a * b);
}

C# 7 Tuples More..

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

which could then be used like this:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

You can also provide names to your elements (so they are not “Item1”, “Item2” etc). You can do it by adding a name to the signature or the return methods:

(string first, string middle, string last) LookupName(long id) // tuple elements have names

or

return (first: first, middle: middle, last: last); // named tuple elements in a literal

They can also be deconstructed, which is a pretty nice new feature:

(string first, string middle, string last) = LookupName(id1); // deconstructing declaration

Resource

https://stackoverflow.com/questions/748062/return-multiple-values-to-a-method-caller

Convert a Console App to Class Library

The big difference, you can run a console app but you can’t run a class library. Usually, Console App has Program.cs file and will compile to .exe file, a class library by default is not executable and will compile to a .dll. In .NET Core console app can also compile to DLL.

A Console App has a flow and can be executed. A Class Library is just a collection of functions that you call from another source. Class libraries by themselves are pretty useless without something to call the functions inside them.

Console App has a static MAIN method that’s an entry point. When deciding to make a method or Static class, I always keep this in mind.

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.

Create console app. Add a greeting method. Run the app. Switch the output type to Class Libarary. Right-Click on Project -> Properties;

Before;

After;

You have best of the both worlds.