Thursday, February 29, 2024

Ups oauth2.0 in c# get rates list || ups api integration c# || c# oauth 2.0 client example

 using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Threading.Tasks;


namespace Ups1

{

    public class Program

    {


        static void Main()

        {


            string client_id = "clientid";

            string client_secret = "clientSecret";

        

            string ups_account_number = "AccountNumber"; 


            // ***** SHIPPING SERVICE AVAILABLE OPTIONS *****

            // Domestic

            // 14 = UPS Next Day Air Early

            // 01 = UPS Next Day Air

            // 13 = UPS Next Day Air Saver

            // 59 = UPS 2nd Day Air A.M.

            // 02 = UPS 2nd Day Air

            // 12 = UPS 3 Day Select

            // 03 = UPS Ground

            // International

            // 11 = UPS Standard

            // 07 = UPS Worldwide Express

            // 54 = UPS Worldwide Express Plus

            // 08 = UPS Worldwide Expedited

            // 65 = UPS Worldwide Saver

            // 96 = UPS Worldwide Express Freight

            // 82 = UPS Today Standard

            // 83 = UPS Today Dedicated Courier

            // 84 = UPS Today Intercity

            // 85 = UPS Today Express

            // 86 = UPS Today Express Saver

            // 70 = UPS Access Point Economy


            // ***** PACKAGE TYPE AVAILABLE OPTIONS *****

            // 01 = Bag, 

            // 02 = Box, 

            // 03 = Carton/Piece, 

            // 04 = Crate, 

            // 05 = Drum, 

            // 06 = Pallet/Skid, 

            // 07 = Roll, 

            // 08 = Tube, 


            // PACKAGE


            // var packages = new List<Package>();

           // packages.Add(new Package(0M, 0M, 0M, 60, 0M));


            var package_info = new

            {

                service = "59",

                package_type = "02",

                Weight = "10",

                length = "7",

                width = "4",

                height = "2",

            };


            // SHIPPER

            var shipper_info = new

            {

                account_number = ups_account_number,

                name = "fromaddressname",

                address1 = "addr1",

                address2 = "addr2",

                address3 = "",

                city = "city",

                state = "state",

                zip = "zipcode",

                country = "us",

            };


            // FROM ADDRESS

            var from_address_info = new

            {

                name = "fromaddressname",

                address1 = "addr1",

                address2 = "addr2",

                address3 = "",

                city = "city",

                state = "state",

                zip = "zipcode",

                country = "US",

            };


            // TO ADDRESS

            var to_address_info = new

            {

                name = "Thomas Jefferson",

                address1 = "931 Thomas Jefferson Parkway",

                address2 = "",

                address3 = "",

                city = "Charlottesville",

                state = "CO",

                zip = "80125",

                country = "US",

            };


            // Get Token

            var accessToken = GetToken(client_id, client_secret);

             // Use API to get price

            var totalCharges = GetShippingCost(accessToken, shipper_info, to_address_info, from_address_info, package_info);


            // Show Price

            Console.WriteLine("Total Charges: $" + totalCharges);

        }


        //static string GetToken(string client_id, string client_secret)

        //{

        //    var combineUserAndPassword = client_id + ":" + client_secret;

        //    var payload = "grant_type=client_credentials";

        //    var authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(combineUserAndPassword));


        //    using (var client = new HttpClient())

        //    {

        //        //client.DefaultRequestHeaders.Add("Content-Type", "application/json");

        //        client.DefaultRequestHeaders.Add("x-merchant-id", "string");

        //        client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);


        //        var response = client.PostAsync("https://wwwcie.ups.com/security/v1/oauth/token", new StringContent(payload, Encoding.UTF8, "application/json")).Result;

        //        var result = response.Content.ReadAsStringAsync().Result;


        //        // Convert the JSON response string to an associative array

        //        var responseArray = JObject.Parse(result);


        //        // Extract the access token

        //        var accessToken = responseArray["access_token"].ToString();

        //        return accessToken;

        //    }

        //}

        static string GetToken(string client_id, string client_secret)

        {

            var combineUserAndPassword = client_id + ":" + client_secret;

            var payload = "grant_type=client_credentials";

            var authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(combineUserAndPassword));


            using (var client = new HttpClient())

            {

                client.DefaultRequestHeaders.Add("x-merchant-id", "string");

                client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);


                var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");

                var response = client.PostAsync("https://wwwcie.ups.com/security/v1/oauth/token", content).Result;

                var result = response.Content.ReadAsStringAsync().Result;


                // Check if the request was successful

                if (!response.IsSuccessStatusCode)

                {

                    // Handle error, log, or throw an exception

                    Console.WriteLine("Token request failed: " + result);

                    return null;

                }


                // Convert the JSON response string to an associative array

                var responseArray = JObject.Parse(result);


                // Explicitly check for null before extracting the access token

                var accessTokenTokenProperty = responseArray["access_token"];

                var accessToken = accessTokenTokenProperty != null ? accessTokenTokenProperty.ToString() : null;


                return accessToken;

            }

        }


        static decimal GetShippingCost(string accessToken, dynamic shipper_info, dynamic to_address_info, dynamic from_address_info, dynamic package_info)

        {

            var version = "v1601";

            var requestOption = "Shop";

            var query = new System.Collections.Generic.Dictionary<string, string>();


            using (var client = new HttpClient())

            {

                var payload = new

                {

                    RateRequest = new

                    {

                        Request = new

                        {

                            TransactionReference = new

                            {

                                CustomerContext = "CustomerContext"//,

                                //TransactionIdentifier = "TransactionIdentifier"

                            }

                        },

                        Shipment = new

                        {

                            Shipper = new

                            {

                                Name = shipper_info.name,

                                ShipperNumber = shipper_info.account_number,

                                Address = new

                                {

                                    AddressLine = new[]

                                {

                                    shipper_info.address1,

                                    shipper_info.address2,

                                    shipper_info.address3

                                },

                                    City = shipper_info.city,

                                    StateProvinceCode = shipper_info.state,

                                    PostalCode = shipper_info.zip,

                                    CountryCode = shipper_info.country

                                }

                            },

                            ShipTo = new

                            {

                                Name = to_address_info.name,

                                Address = new

                                {

                                    AddressLine = new[]

                                {

                                    to_address_info.address1,

                                    to_address_info.address1,

                                    to_address_info.address1

                                },

                                    City = to_address_info.city,

                                    StateProvinceCode = to_address_info.state,

                                    PostalCode = to_address_info.zip,

                                    CountryCode = to_address_info.country

                                }

                            },

                            ShipFrom = new

                            {

                                Name = from_address_info.name,

                                Address = new

                                {

                                    AddressLine = new[]

                                {

                                    from_address_info.address1,

                                    from_address_info.address2,

                                    from_address_info.address3

                                },

                                    City = from_address_info.city,

                                    StateProvinceCode = from_address_info.state,

                                    PostalCode = from_address_info.zip,

                                    CountryCode = from_address_info.country

                                }

                            },

                            PaymentDetails = new

                            {

                                ShipmentCharge = new

                                {

                                    Type = "01",

                                    BillShipper = new

                                    {

                                        AccountNumber = shipper_info.account_number

                                    }

                                }

                            },

                            Service = new

                            {

                                Code = package_info.service,

                                Description = "ground"

                            },

                            NumOfPieces = "1",

                            Package = new

                            {

                                PackagingType = new

                                {

                                    Code = package_info.package_type,

                                    Description = "Packaging"

                                },

                                Dimensions = new

                                {

                                    UnitOfMeasurement = new

                                    {

                                        Code = "IN",

                                        Description = "Inches"

                                    },

                                    Length = package_info.length,

                                    Width = package_info.width,

                                    Height = package_info.height

                                },

                                PackageWeight = new

                                {

                                    UnitOfMeasurement = new

                                    {

                                        Code = "LBS",

                                        Description = "Pounds"

                                    },

                                    Weight = package_info.Weight

                                }

                            }

                        }

                    }

                };


                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

                //client.DefaultRequestHeaders.Add("Content-Type", "application/json");

                client.DefaultRequestHeaders.Add("transId", "string");

                client.DefaultRequestHeaders.Add("transactionSrc", "testing");


                var response = client.PostAsync("https://wwwcie.ups.com/api/rating/v1/Rate?{ToQueryString(query)}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")).Result;

                //var response = client.PostAsync("https://wwwcie.ups.com/api/rating/{version}/{requestOption}?{ToQueryString(query)}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")).Result;

                var result = response.Content.ReadAsStringAsync().Result;


                // Convert the JSON response string to an associative array

                var responseArray = JObject.Parse(result);


                // Extract the total charges

                var totalCharges = Convert.ToDecimal(responseArray["RateResponse"]["RatedShipment"]["TotalCharges"]["MonetaryValue"]);

                return totalCharges;

            }

        }


        static string ToQueryString(System.Collections.Generic.Dictionary<string, string> query)

        {

            var array = query.Select(kvp => "{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}").ToArray();

            return "?" + string.Join("&", array);

        }

    }

}


Note : Change your client id , Account Number and client secret and add the correct  from and to address in the above program

After token expire we will get 

this error First = {"response": {

  "errors": [

    {

      "code": "250002",

      "message": "Invalid Authentication Information."

    }

  ]

}}

Monday, February 19, 2024

boxing and unboxing

In C#, boxing and unboxing are concepts related to converting value types (such as int, char, etc.) to reference types (such as object). Let’s explore both concepts with examples:

  1. Boxing:

    • Boxing is the process of converting a value type to the type object or any interface type implemented by that value type.
    • When the Common Language Runtime (CLR) boxes a value type, it wraps the value inside an object instance and stores it on the managed heap.
    • Here’s an example of boxing:
      int i = 123; // The following line boxes 'i'.
      object o = i;
      
    • In this example, the integer variable i is boxed and assigned to the object variable o.
  2. Unboxing:

    • Unboxing is the process of extracting the value type from an object.
    • It converts the object back to its original value type.
    • Example of unboxing:
      o = 123; // Unboxing: extract the value from 'o' and assign it to 'i'.
      int unboxedValue = (int)o;
      
  3. Practical Example:

    • Let’s create a heterogeneous collection using an ArrayList (a dynamically sized array of objects):
      ArrayList mixedList = new ArrayList();
      mixedList.Add("First Group:"); // Add a string element
      for (int j = 1; j < 5; j++)
      {
          mixedList.Add(j); // Add integers (boxing occurs)
      }
      mixedList.Add("Second Group:");
      for (int j = 5; j < 10; j++)
      {
          mixedList.Add(j);
      }
      
      // Display the elements in the list
      foreach (var item in mixedList)
      {
          Console.WriteLine(item);
      }
      
      // Calculate the sum of squares of the first group of integers
      var sum = 0;
      for (var j = 1; j < 5; j++)
      {
          sum += (int)mixedList[j] * (int)mixedList[j]; // Unboxing
      }
      Console.WriteLine($"Sum: {sum}"); // Output: Sum: 30
      
    • In this example, we box integers when adding them to the ArrayList and unbox them during the sum calculation.

Remember that boxing and unboxing have performance implications, so use them judiciously.

Sunday, February 18, 2024

what is asp.net mvc framework

 The ASP.NET MVC (Model-View-Controller) framework is an architectural and design pattern used for developing web applications. Let’s break down what it entails:

  1. Model: The Model component represents the data-related logic in the application. It handles data retrieval, storage, and manipulation. For instance, it can interact with a database or manage business logic.

  2. View: The View component is responsible for the user interface (UI) logic. It generates the visual representation that users interact with. Views are created based on data provided by the Model, but they communicate with the Controller.

  3. Controller: The Controller acts as an intermediary between the Model and the View. It processes incoming requests, manipulates data using the Model, and instructs the View on how to render the final output. The Controller doesn’t handle data logic directly; instead, it orchestrates the flow.

Here are some key points about ASP.NET MVC:

  • Clean Separation: ASP.NET MVC promotes a clean separation of concerns. By dividing the application into distinct components (Model, View, and Controller), developers can manage complexity more effectively.

  • Scalability and Extensibility: It’s a powerful framework for building scalable and extensible projects. Developers can create robust web applications that are easy to maintain.

  • URL Control: ASP.NET MVC provides control over URLs, making it straightforward to design web application architectures with comprehensible and searchable URLs.

  • Test Driven Development (TDD): The framework supports TDD, allowing developers to write tests for their code and ensure its correctness.

Overall, ASP.NET MVC is widely used in industry-standard web development and is also suitable for designing mobile apps.

Thursday, February 15, 2024

Interface

  1. What Is an Interface in C#?

    • An interface in C# is a fully unimplemented class used for declaring a set of operations or methods that an object must provide.
    • It serves as a pure abstract class, allowing us to define only abstract methods (methods without a body).
    • Interfaces are used to achieve multiple inheritances, which classes cannot achieve directly.
    • They also ensure full abstraction because interface methods cannot have a method body.
    • In C#, an interface is a fundamental concept defining a contract or a set of rules that a class must adhere to.
    • It specifies a list of methods, properties, events, or indexers that a class implementing the interface must provide.
    • Interfaces allow you to define a common set of functionality that multiple classes can share, promoting code reusability and ensuring a consistent structure for related classes.
  2. Differences Between Concrete Class, Abstract Class, and Interface in C#:

    • Concrete Class:
      • Contains only non-abstract methods (methods with a method body).
    • Abstract Class:
      • Contains both non-abstract methods and abstract methods (methods without a method body).
    • Interface:
      • Contains only abstract methods (methods without a method body).
  3. Real-World Example: Library Management System

    • Imagine building a Library Management System where you need to handle different types of library items (books, DVDs, etc.).

    • We can define an interface called ILibraryItem to specify common behavior for all library items:

      interface ILibraryItem
      {
          string Title { get; set; }
          void CheckOut(string borrower);
          void Return();
      }
      
    • Now, let’s implement this interface for specific library items:

      • Book:

        class Book : ILibraryItem
        {
            public string Title { get; set; }
        
            public void CheckOut(string borrower)
            {
                // Logic for checking out a book
            }
        
            public void Return()
            {
                // Logic for returning a book
            }
        }
        
      • DVD:

        class DVD : ILibraryItem
        {
            public string Title { get; set; }
        
            public void CheckOut(string borrower)
            {
                // Logic for checking out a DVD
            }
        
            public void Return()
            {
                // Logic for returning a DVD
            }
        }
        
    • By using the ILibraryItem interface, we ensure that all library items adhere to the same contract, allowing consistent handling across different types of items.

    • Interfaces promote code reusability, maintainability, and a consistent structure for related classes. 

Remember, interfaces provide a powerful way to define contracts and encourage good design practices in your C# code!

Tuesday, February 6, 2024

Introduction to C#

 Certainly! C# (pronounced “C-Sharp”) is a powerful and versatile programming language created by Microsoft. Let’s explore some key points about C#:

  1. What is C#?

    • C# is an object-oriented programming language that runs on the .NET Framework.
    • It has its roots in the C family of languages and shares similarities with C++, Java, and JavaScript.
    • The first version of C# was released in 2002, and the latest version (C# 12) arrived in November 2023.
    • C# is used for a wide range of applications, including:
      • Mobile applications
      • Desktop applications
      • Web applications
      • Web services
      • Games
      • Database applications
      • And much more!
  2. Why Use C#?

    • Popularity: C# is one of the most popular programming languages globally.
    • Ease of Learning: It is easy to learn and has a straightforward syntax.
    • Community Support: C# has a large and active community.
    • Object-Oriented: C# provides a clear structure to programs, allowing code reuse and lowering development costs.
    • Familiarity: If you know C, C++, or Java, transitioning to C# is relatively straightforward.
  3. Getting Started:

    • You don’t need prior programming experience to learn C#.
    • Explore tutorials, videos, and interactive lessons to grasp the basics of C#.
    • Whether you’re building web apps, desktop software, or games, C# offers a robust foundation for your projects.

Happy coding! 🚀 If you’re ready to dive in, you can start learning C# through resources like W3SchoolsMicrosoft’s .NET Learn, or Microsoft Learn’s C# tutorials

AVS settings Authorize.Net account

Certainly! Configuring the Address Verification Service (AVS) settings in your Authorize.Net account is essential for fraud prevention and ensuring secure credit card transactions. Let’s walk through the steps:

  1. Log In to the Merchant Interface:

    • Access the Authorize.Net Merchant Interface using your credentials.
  2. Navigate to AVS Settings:

    • Once logged in, follow these steps:
      • Click on Account.
      • Under Basic Fraud Settings, select Address Verification Service.
  3. Review and Adjust AVS Response Codes:

    • You’ll see a list of AVS response codes. These codes indicate the results of matching the billing address provided by the cardholder with the address on file at the credit card issuing bank.
    • Here are some common AVS response codes:
      • B: Address information not submitted in the transaction.
      • E: Invalid AVS data or AVS not allowed for the card type.
      • R: AVS unavailable during transaction processing (retry later).
      • G: Non-U.S. card issuing bank (does not support AVS).
      • U: Address information not available for the customer’s credit card.
      • S: U.S. card issuing bank does not support AVS.
      • N: Neither street address nor 5-digit ZIP code matches.
      • A: Street address matches, but ZIP code does not.
      • Z: First 5 digits of ZIP code match, but street address does not.
      • W: 9-digit ZIP code matches, but street address does not.
      • Y: Street address and first 5 digits of ZIP code match perfectly.
  4. Configure Your AVS Rejection Settings:

    • Decide which AVS response codes you want to use for rejecting transactions.
    • Follow these steps:
      • Click the checkbox next to each AVS response code you want to reject.
      • Click Submit to apply your settings.
      • A confirmation message will indicate that your changes have been successfully applied.
  5. Important Considerations:

    • AVS is not foolproof and should not be solely relied upon for absolute protection against suspicious transactions.
    • Be aware that some legitimate transactions may be declined due to AVS settings.
    • Carefully assess your business’s risk level when configuring AVS mismatch rejection settings.

Remember that AVS helps enhance security, but it’s essential to strike a balance between fraud prevention and customer experience. Most banks and Merchant Service Providers recommend using AVS to avoid non-qualified transaction surcharges. Happy configuring! 🛡️🔒

Thursday, November 23, 2023

ReactJS

 Here are some common ReactJS interview questions and answers:

Q1. What is ReactJS?

A1. ReactJS is an open-source, front-end JavaScript library developed by Facebook for building user interfaces or UI components. It follows the component based approach which helps in building reusable UI components.

Q2. What are the major features of ReactJS?

A2. Major features include:

- It uses VirtualDOM instead of RealDOM which is faster.

- It follows uni-directional data flow or one-way data binding.

- It uses reusable/composable UI components to develop the view.

- It is used for handling view layer only while Redux is used for state management.

- It uses server-side rendering for faster page load and better SEO.

Q3. What is JSX? 

A3. JSX is a HTML/XML-like syntax extension to JavaScript which is used in React for easily describing UI components. It is not valid JavaScript but gets transformed to JavaScript with transpilers like Babel. It makes code easy to read and write.

Q4. Difference between class and functional components

A4. Class components use ES6 class and render() method to return elements. Functional components use normal JavaScript functions to return elements. With hooks, functional components can now also use state and other features which were only for class components earlier.

Q5. What are state and props in React?

A5. State represents data maintained inside a component while props represent data passed from a parent component to a child component which is read-only for the receiving component. State data can be changed but triggers render while props are immutable.

ASP.NET Core

 Here are some more ASP.NET Core MVC interview questions:

Q1. What is view compilation in ASP.NET Core MVC and why is it useful?

A1. View compilation converts Razor views to C# classes during application startup. This avoids compilation overhead at runtime, improving response time. It is enabled by setting RazorCompileOnBuild to true.

Q2. How do you handle errors and exceptions in ASP.NET Core web APIs? 

A2. Using middleware such as app.UseExceptionHandler() to catch errors and return consistent error responses. We can also use filters like [ApiExplorer] for handling errors at controller action level.

Q3. What is model validation in ASP.NET Core MVC?

A3. Validating model properties based on validation attributes like [Required], [MaxLength] etc. applied to the model class. Validation is automatically triggered and error messages displayed in views using ValidationSummary, ValidationFor helpers.

Q4. How do you implement localization in ASP.NET Core MVC application?

A4. By configuring localization services in Startup. We define resource files per culture, configure localization middleware, call CreateLocalizationConvention to specify resource file locations. Use IStringLocalizer to access localized strings.

Q5. What are the differences between .NET Core and .NET Framework Runtime? 

A5. .NET Core is cross-platform, lightweight and supports more modern application scenarios like containers/microservices. .NET Framework supports older application models like WPF desktop apps, Windows workflows - limited to Windows.

Q6. What is middleware in ASP.NET Core and how does it work?

A6. Middleware are components that are part of the app pipeline that handle HTTP requests/responses. Multiple middleware are chained together using Use() in Configure() method. Pipeline flows through each middleware sequentially.

Q7. What are the main advantages of using ASP.NET Core over ASP.NET MVC?

A7. Cross-platform support, better performance, integration with modern client-side frameworks, lightweight and modular architecture due to middleware, configuration via C# code.

ASP.NET Core MVC || MVC

 Here are some additional ASP.NET Core MVC interview questions:

Q1. What is routing in ASP.NET Core MVC and how does it work?

A1. Routing is used to map incoming HTTP requests to particular MVC controller actions. The Configure() method in Startup.cs file adds endpoint routing middleware that maps request URLs to routing templates defined using attributes like [Route] and controllers.

Q2. How do you manage state in an ASP.NET Core application?

A2. ASP.NET Core is stateless by default. To manage state, we can use sessions by adding session middleware. State can also be stored in databases or external state cache like Redis. 

Q3. What is the file-based authorization policy in ASP.NET Core?

A3. It allows authorizing users against user roles defined in a JSON file rather than in app code. We create a JSON file mapping users to roles and configure the Authorization service to use the policy in Startup.cs.

Q4. How are model bindings used in ASP.NET Core MVC?

A4. Model binding automatically maps form data and route data from an HTTP request to parameters in a controller action. We just need to define the parameter name same as input field in a form or route parameter.

Q5. What is view composition in ASP.NET Core MVC?

A5. Building a view using both a main view and partial views defined in separate Razor view files. The main view can render HTML sections defined in partial views using @await Html.PartialAsync() method.

Q6. How do you serve static files in ASP.NET Core web apps?

A6. Using built-in middleware by configuring it through methods like app.UseStaticFiles() in Startup.cs. We define a static file path, set caching headers for static files etc.

Q7. How do you implement logging in ASP.NET Core apps?

A7. Using ILogger interface injected into classes needing logging. Log messages written through ILogger will be directed to logging providers configured in Startup - like console, debug, file, Azure App Insights etc.

ASP.NET Core MVC || Core

 Here are some additional ASP.NET Core MVC interview questions and answers:

Q1. What is Razor in ASP.NET Core MVC?

A1. Razor is a view engine for rendering views. It allows you to mix C# or Visual Basic code with HTML markup in Razor View (.cshtml file) to build UI.

Q2. What are Tag Helpers in ASP.NET Core MVC?

A2. Tag Helpers allow you to add server-side logic to existing HTML tags using attributes designed for that specific tag. They are processed on the server before any client-side frameworks like React or Angular get them.

Q3. How do you handle security in ASP.NET Core MVC applications?  

A3. Some ways to handle security include:

- Authentication - Identity library, Azure AD, OAuth/OpenID 

- Authorization - Role-based or policy-based authorization

- HTTPS

- CORS

- Input validation

Q4. What is caching? How can we implement caching in ASP.NET Core?

A4. Caching is storing data/page output temporarily so that future requests can be served faster. We can implement in-memory caching using IMemoryCache interface or a distributed cache like Redis. The data has an expiration period and gets invalidated after that.

Q5. How do you configure linking between MVC views and actions?

A5. Using attribute routing to provide named routes like [Route("[controller]/[action]")]. We generate links using these named routes with Url.Action() or <a asp-action="">

Q6. What is JSON serialization and how do you implement it in ASP.NET Core?

A6. Converting a .NET object to JSON format. We can use JsonSerializer class or in ASP.NET Core, adding [ApiController] attribute handles serialization automatically using System.Text.Json library.

Q7. What is view injection in ASP.NET Core MVC?

A7. Dependency injecting a view component into a view via the @inject directive so that we can call methods on that injected class directly from the view.