Scott Harrison - The golden apples
Henry Parker's Robot Wars

ASP.Net, ADO, MS Access
c# how to call a webapi from mvc angular 2 component

c# how to call a webapi from mvc angular 2 component

(23 hits)
OverView: Hits=9 In this code sample, I have two projects, one is an Angular 2 component project for the web interface and the other is the web api project with the entity framework code first classes, unit of work, and fluent code modules. I will demonstrate how create a connection between the angular project and the web api project.

When testing or debugging webapi using xunit, make sure to change the appsettings.json property "Copy to output directory" to "always" because by default it is never. Otherwise you get the missing appsetting.json generates an error while referencing class methods in your web api.

Hits=8 Overview of the process flow begins with angular component making a get request to an local web api controller called budgetController this mvc webapi controller then calls the lssWebApiController using a dataservice class that I created and invokes the budget module query to return a list of budgets. The returning dataset is returned as a json string and assigned to an typescript interface and consumed in the angular report.

Hits=8 The @Inject('BASE_URL') dependency injects the base url of the angular program. In my solution, I multi start the lssAngular and lssWebApi projects with the lssWebApi starting first. The BudgetController by convention is Budget and restful rules apply. So a get without an parameter will return a collection of List<BudgetViews>. The javascript method .subscribe works like an promise returning data results once the lssWebapi completes its task. The angular IBudgetView should match the field names and types of the C# BudgetViewClass. The typescript interface is used to define the data shape of the result.

Hits=6 The lssWebApi baseurl is stored in the dataservice class. The WebApi on the lssWebApi assembly is called using the httpClient in the dataservice class. The api path on the lssWebapi assembly is invoking using the httpClient.GetAsync method and it awaits the results from the assembly.

Hits=6 The Datacontext is initialized as lazying loading for the class mappings to retrieve data from entity framework code first classes. Authentication credentials are stored in the appsetting.json.

Hits=4 The lssWebApi Budget Controller route is discovered and the httpGet Get is execute. Within the Get method a fluent class called BudgetModule is instantiated and the its classed called FluentBudgetQuery interface method Query() is invoked. The Query method calls its unit of Work class which calls its budgetRepository method GetBudgetViews. The repository method GetBudgetViews uses the datacontext to access the budgets dbset and returns a IEnumerable list of BudgetViews using a linq statement. The lazy loading allows access to the parent data of the entity frame work class budget.

Hits=2 The lazyloading allows access to the foreign key data. for example, budget.Account.Description is references the foreign key table Chart Of Accounts. Using the accountid a relationship is established between the budget table and the chartofAcct table.

lssAngular Angular Component


import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-budget-webapi',
  templateUrl: './budget-webapi.component.html'
})



export class BudgetWebApiComponent {
  public budgets: IBudgetView[];

  constructor(
    http: HttpClient, @Inject('BASE_URL') baseUrl: string) {

    http.get<IBudgetView[]>(baseUrl + 'api/Budget').subscribe(result => {

      this.budgets = result;
  
    }, error => console.error(error));

    }

interface IBudgetView {
  budgetId: number;
  budgetHours: number;
  budgetAmount: number;
  actualHours: number;
  actualAmount: number;
  accountId: number;
  accountDescription: string;
  companyNumber: string;
  busUnit: string;
  objectNumber: string;
  subsidiary: string;
  rangeId: number;
  rangeStartDate: Date;
  rangeEndDate: Date;
  companyCode: string;
  supervisorCode: string;
  projectedHours: number;
  projectedAmount: number;
}

lssAngular DataService class


 public class DataService
    {
        string Baseurl = "http://localhost:61612";

        public async Task<T> GetAsync<T>(string apiPath)
        {
            T view = default(T);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Baseurl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage Res = await client.GetAsync(apiPath);

                if (Res.IsSuccessStatusCode)
                {
                    var Response = Res.Content.ReadAsStringAsync().Result;
                    view = JsonConvert.DeserializeObject<T>(Response);

                }

            }
            return view;
        }
    }

lssAngular WebApi BudgetController


 [Route("api/[controller]")]
    public class BudgetController : Controller
    {
        
        // GET: api/<controller>
        [HttpGet("{budgetId}")]
        public async Task<BudgetView> Get(long budgetId)
        {
            DataService ds = new DataService();
            BudgetView view =  await ds.GetAsync<BudgetView>("api/Budget/" + budgetId.ToString());
          
            return view;
        }

        [HttpGet()]
        public async Task<List<BudgetView>> Get()
        {
            DataService ds = new DataService();
            List<BudgetView> views = await ds.GetAsync<List<BudgetView>>("api/Budget");
          
            return views;
        }

lssWebAPI Listensoftware Datacontext


    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
		//other ways to get the Directory path of the application
                //var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //var basePath = AppDomain.CurrentDomain.BaseDirectory;
      		//var environmentPath = Environment.CurrentDirectory;
                //var assemblyPath = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

                var directoryPath = Directory.GetCurrentDirectory();
        

                IConfigurationRoot configuration = new ConfigurationBuilder()
                       .SetBasePath(directoryPath)
                       .AddJsonFile("appsettings.json")
                       .Build();
                var connectionString = configuration.GetConnectionString("DbCoreConnectionString2");
                optionsBuilder.UseLazyLoadingProxies().UseSqlServer(connectionString);

            }
        }

lssWebApi Web Api Budget Controller Get

//budgetController.cs

namespace lssWebApi2.Controllers
{
    [Route("api/[Controller]")]
    public class BudgetController : Controller
    {
        [HttpGet("{budgetId}")]
        public BudgetView Get(long budgetId)
        {

            BudgetModule budgetMod = new BudgetModule();

            BudgetView budgetView = budgetMod.Budget.Query().GetBudgetView(budgetId);

            return budgetView;
        }
        [HttpGet]
        public IEnumerable<BudgetView> Get()
        {
     

            BudgetModule budgetMod = new BudgetModule();

            IEnumerable<BudgetView> budgetViews = budgetMod.Budget.Query().GetBudgetViews();

            return budgetViews;

        }
}

FluentBudget

 public class FluentBudget : AbstractModule, IBudget
    {
        UnitOfWork unitOfWork = new UnitOfWork();
        CreateProcessStatus processStatus;

        FluentBudgetQuery _query = null;
        public IBudgetQuery Query()
        {
            if (_query == null)
            {
                _query = new FluentBudgetQuery(unitOfWork);
            }
            return _query as IBudgetQuery;
        }
        public IBudget MapRangeToBudgetView(ref BudgetView budgetView, BudgetRangeView budgetRangeView)
        {
            unitOfWork.budgetRepository.MapRangeToBudgetView(ref budgetView, budgetRangeView);
            return this as IBudget;
        }
        public IBudget TransactBudget(BudgetView budgetView)
        {
            try
            {
                Task resultStatus = Task.Run(async () => await unitOfWork.budgetRepository.TransactBudget(budgetView));
                Task.WaitAll(resultStatus);
                processStatus = resultStatus.Result;
                return this as IBudget;
            }
            catch (Exception ex) { throw new Exception(GetMyMethodName(), ex); }


        }
        public IBudget Apply()
        {
            try
            {
                if ((processStatus == CreateProcessStatus.Insert) || (processStatus == CreateProcessStatus.Update) || (processStatus == CreateProcessStatus.Delete))
                {
                    unitOfWork.CommitChanges();
                }
                return this as IBudget;
            }
            catch (Exception ex) { throw new Exception(GetMyMethodName(), ex); }

        }
    }

FluentBudgetQuery


 public IEnumerable<BudgetView> GetBudgetViews()
        {
            Task<List<BudgetView>> budgetViewsTask = Task.Run(async () => await _unitOfWork.budgetRepository.GetBudgetViews());
            Task.WaitAll(budgetViewsTask);
            return budgetViewsTask.Result;
        }

lssWebApi Unit of Work

  public async Task<List<BudgetView>> GetBudgetViews()
        {
            try
            {
                var query = await (from e in _dbContext.Budget
                                       select e).ToListAsync<Budget>();

                List<BudgetView> budgetViews = new List<BudgetView>();
                BudgetView budgetView = null;
                foreach(var budget in query)
                {
                    budgetView = applicationViewFactory.MapBudgetView(budget);
                    budgetViews.Add(budgetView);
                }
                return budgetViews;
            }
            catch (Exception ex) { throw new Exception(GetMyMethodName(), ex); }
        }

lssWebApi Abstract View Factory

public override BudgetView MapBudgetView(Budget budget)
        {
            return new BudgetView(budget);
        }

lssWebApi BudgetView class

  public class BudgetView
    {
        public BudgetView() { }
        public BudgetView(Budget budget)
        {
            this.BudgetId = budget.BudgetId;
            this.BudgetHours = budget.BudgetHours;
            this.BudgetAmount = budget.BudgetAmount;
            this.ActualHours = budget.ActualHours;
            this.ActualAmount = budget.ActualAmount;
            this.AccountId = budget.AccountId;
            this.AccountDescription = budget.Account.Description;
            this.CompanyNumber = budget.Account.CompanyNumber;
            this.BusUnit = budget.Account.BusUnit;
            this.ObjectNumber = budget.Account.ObjectNumber;
            this.Subsidiary = budget.Account.Subsidiary;
            this.RangeId = budget.RangeId;
            this.RangeStartDate = budget.Range.StartDate;
            this.RangeEndDate = budget.Range.EndDate;
            this.CompanyCode = budget.Range.CompanyCode;
            this.SupervisorCode = budget.Range.SupervisorCode;
            this.ProjectedHours = budget.ProjectedHours;
            this.ProjectedAmount = budget.ProjectedAmount;
        }
        public long BudgetId { get; set; }
        public decimal? BudgetHours { get; set; }
        public decimal? BudgetAmount { get; set; }
        public decimal? ActualHours { get; set; }
        public decimal? ActualAmount { get; set; }
        public long? AccountId { get; set; }
        public string AccountDescription { get; set; }
        public string CompanyNumber { get; set; }
        public string BusUnit { get; set; }
        public string ObjectNumber { get; set; }
        public string Subsidiary { get; set; }
        public long? RangeId { get; set; }
        public DateTime? RangeStartDate { get; set; }
        public DateTime? RangeEndDate { get; set; }
        public string CompanyCode { get; set; }
        public string SupervisorCode { get; set; }
        public decimal? ProjectedHours { get; set; }
        public decimal? ProjectedAmount { get; set; }
    }
....

...<<<Register to correspond>>> ...

Members : 152
Name:
Email:

Register to View

Help