In this blog, I am going to illustrate an end-to-end solution
(service > back-end > front-end) to create a new .NET Core web service and
consume that service by the front-end. I will be demonstrating step-by-step how to
develop a RESTful Web Service application in ASP.NET Core and connect that service to SQL Server using Entity Framework and consume by front-end UI
developed in HTML using JavaScript.
I will be creating a Training Service as an example in my complete course to demonstrate Web Service, Entity Framework, and a few front-end concepts. The front-end will provide a UI to list all the training details in table form using REST API and another form with input fields as name, start date, end date, and confirm Submit button. On confirmation, the REST API should save the new training details into the database.
Let's start with Visual Studio to create a new web service (REST) application using .NET Core.
1. Open VS, go to File > New and select Project > ASP .NET Core Web Application. Select the solution name (e.g. Training service) and the location of your local directory. Click ok.

2. Select the API for creating REST API using default example valuecontroller(can be deleted later). You can uncheck the 'Configure for HTTPS' checkbox because that creates SSL-based project and you have to use HTTPS instead of HTTP in your URLs (this is an optional step).

3. Click ok and you should see the below project structure.

4. Let's setup the Entity framework Model for sql server to create one table i.e. tblTraining having three properties Name(char[256)), StartDate(datetime), EndDate(datetime).
- CREATE TABLE [dbo].[TblTraining] (
- [Name] CHAR (256) NOT NULL,
- [StartDate] DATETIME NOT NULL,
- [EndDate] DATETIME NULL,
- PRIMARY KEY CLUSTERED ([Name] ASC)
- );
You can use also VS to setup entity framework and setup the Model, I am not adding more steps here for entity framework and it is not the scope of this article. Once your Model is ready take the connection string.
If you already have any existing framework then just add this new table for test and execute the below command.
- scaffold-DBContext "your connection string which start with Data Source= ……………….." Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -tables tblTraining
- public partial class tempdbContext : DbContext
- {
- public tempdbContext()
- {
- }
- public tempdbContext(DbContextOptions<tempdbContext> options)
- : base(options)
- {
- }
- public virtual DbSet<TblTraining> TblTraining { get; set; }
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- if (!optionsBuilder.IsConfigured)
- {
- #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
- optionsBuilder.UseSqlServer("Data Source=(localdb)\\LocalUAP;Initial Catalog=tempdb;Integrated Security=True");
- }
- }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
- modelBuilder.Entity<TblTraining>(entity =>
- {
- entity.HasKey(e => e.Name);
- entity.Property(e => e.Name)
- .HasMaxLength(256)
- .IsUnicode(false)
- .ValueGeneratedNever();
- entity.Property(e => e.EndDate).HasColumnType("date");
- entity.Property(e => e.StartDate).HasColumnType("date");
- });
- }
- }
- public partial class TblTraining
- {
- public string Name { get; set; }
- public DateTime StartDate { get; set; }
- public DateTime? EndDate { get; set; }
- }
- public class TrainingViewModel
- {
- public string EndDate { get; set; }
- public string StartDate { get; set; }
- public string Name { get; set; }
- }
5. Open the Startup.cs and setup the connection with the database for this webservice. In my case, my database name is tempdb which created tempdbContext. Add below code in your ConfigureServices method.
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
- var connection = "your connection string here start with Data Source=….";
- services.AddDbContext<tempdbContext>(o => o.UseSqlServer(connection));
- services.AddScoped<ITrainingServices, TrainingServices>();
- }
6. Next, you can use the internal services/helper concept to read/validate the data when service requests for it. I have created ITrainingServices interface and corresponding service class TrainingServices which use database context to manage the data. Using this approach, you can also create one local service (LocalTrainingServices) which is independent of db context, and keeps values in memory for testing. If you have not established entity framework yet in that case you can use this local service as Scope in startup.cs. Replace AddScoped<> line in startup.cs with below code.
services.AddScoped<ITrainingServices, LocalTrainingServices>();
- public interface ITrainingServices
- {
- Task<IList<TrainingViewModel>> GetTrainingData();
- TrainingViewModel GetTrainingData(string name);
- bool CreateTraining(TrainingViewModel viewModel);
- void Delete(string name);
- }
- public class TrainingServices : ITrainingServices
- {
- private readonly tempdbContext dbcontext;
- public TrainingServices(tempdbContext context)
- {
- this.dbcontext = context;
- }
- public async Task<IList<TrainingViewModel>> GetTrainingData()
- {
- return await dbcontext.TblTraining.Select(s => new TrainingViewModel() { Name = s.Name, StartDate = s.StartDate.ToString(), EndDate = s.EndDate.ToString() }).ToListAsync();
- }
- public TrainingViewModel GetTrainingData(string name)
- {
- var s = dbcontext.TblTraining.FirstOrDefault(d => d.Name == name);
- if (s == null)
- {
- return null;
- }
- return new TrainingViewModel { Name = s.Name, StartDate = s.StartDate.ToString(), EndDate = s.EndDate.ToString() };
- }
- public async void Delete(string name)
- {
- var s = dbcontext.TblTraining.FirstOrDefault(d => d.Name == name);
- if (s == null)
- {
- return;
- }
- dbcontext.TblTraining.Remove(s);
- await dbcontext.SaveChangesAsync();
- }
- public bool CreateTraining(TrainingViewModel viewModel)
- {
- try
- {
- var start = DateTime.Parse(viewModel.StartDate);
- var end = DateTime.Parse(viewModel.EndDate);
- if (start < end)
- {
- return false;
- }
- dbcontext.TblTraining.Add(new TblTraining() { Name = viewModel.Name, StartDate = start, EndDate = end });
- int count = dbcontext.SaveChanges();
- if (count > 0)
- {
- return true;
- }
- return false;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- }
- public class LocalTrainingServices : ITrainingServices
- {
- private static readonly List<TrainingViewModel> trainingViewModels = new List<TrainingViewModel>()
- {
- new TrainingViewModel() {Name = "c#", StartDate = "2012-01-01", EndDate = "2012-12-01"},
- new TrainingViewModel() {Name = "java", StartDate = "2013-01-01", EndDate = "2014-12-01"},
- new TrainingViewModel() {Name = "python", StartDate = "2018-01-01", EndDate = "2018-12-01"},
- };
- public Task<IList<TrainingViewModel>> GetTrainingData()
- {
- return new Task<IList<TrainingViewModel>>(() => trainingViewModels);
- }
- public TrainingViewModel GetTrainingData(string name) =>
- trainingViewModels.FirstOrDefault(d => d.Name == name);
- public void Delete(string name)
- {
- var s = trainingViewModels.FirstOrDefault(d => d.Name == name);
- if (s == null)
- {
- return;
- }
- trainingViewModels.Remove(s);
- }
- public bool CreateTraining(TrainingViewModel viewModel)
- {
- if (GetTrainingData(viewModel.Name) == null)
- {
- trainingViewModels.Add(viewModel);
- return true;
- }
- return false;
- }
- }




duoi chonPosted Sep 29, 2020, 10:42 AM
Please help post raise 'Unsupported Media Type'. If use 'Content-Type': 'application/json' then raise 'from origin 'null' has been blocked by CORS policy'
dan varzaruPosted Mar 3, 2020, 11:52 AM
Hi Ashutosh, is it possible to UPDATE a record ?
Sourav Kumar DasPosted Sep 27, 2019, 11:18 PM
Superb Article Bro