In Day 6 - Routing, we mocked the customer data in the frontend but not the database. We will use Angular2 Http module and ASP.NET core – web api to fulfill the CRUD functions with data stored in database (in this example, it's sql server).
This article will separated into two parts:
Create an ASP.NET core Web application as Web api. What we will do before implementing the CRUD functions in frontend:
Please refer to this article: Day 9 - NLog and jsnlog
Required package : Microsoft.AspNetCore.Cors
We will enable the global CORS settings in Startup.cs
.
For more detail settings, visit here - Enabling Cross-Origin Requests (CORS)
public void ConfigureServices(IServiceCollection services)
{
//Step1. Enable CORS
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
builder.WithOrigins("http://localhost:4240") //Or AllowAnyOrigin()
.WithMethods("GET", "POST", "PUT", "DELETE") //Or AllowAnyMethod()
);
});
//Step2. Enable CORS for every MVC actions
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//…
app.UseCors("AllowSpecificOrigin");
}
If you don’t want to enable a policy on every web api action (http method), ignore step 2. And specify the CORS policy on an action with [EnableCors]
attribute like this.
[EnableCors("AllowSpecificOrigin")]
public async Task<HttpResponseMessage> Create([FromBody]Customer cust)
{}
Or use [DisableCors]
for security issue.
Web api will default return the json
object with lower-Camel-case property names, even if the properties are in Pascal case.
For example, my class’s properties are Pascal case,
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public int Age { get; set; }
public string Description { get; set; }
}
But web api returns lower Camel case.
So we add the following configuration to solve this issue.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
options.SerializerSettings.Formatting = Formatting.None; //or Formatting.Indented for readability;
});
//…
}
See the updated result.
Required : Microsoft.EntityFrameworkCore.SqlServer
Also have a look at these related articles.
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(100)]
[Required]
public string Name { get; set; }
[StringLength(100)]
public string Phone { get; set; }
public int Age { get; set; }
[StringLength(200)]
public string Description { get; set; }
}
public class NgDbContext : DbContext
{
public NgDbContext(DbContextOptions options) : base(options)
{}
public DbSet<Customer> Customers { get; set; }
}
public class CustomerService:IDisposable
{
private NgDbContext _dbContext = null;
public CustomerService(NgDbContext dbContext)
{
this._dbContext = dbContext;
}
public IQueryable<Customer> GetAll()
{
return this._dbContext.Customers;
}
public IQueryable<Customer> Get(Expression<Func<Customer, bool>> filter)
{
return this._dbContext.Customers.Where(filter);
}
public void Add(Customer entity)
{
this._dbContext.Customers.Add(entity);
this._dbContext.SaveChanges();
}
public void Update(Customer entity)
{
this._dbContext.SaveChanges();
}
public void Remove(Customer entity)
{
this._dbContext.Customers.Remove(entity);
this._dbContext.SaveChanges();
}
}
Okay, everything is done. We are going to implement the CRUD http methods in web api
.
Okay, the following is a normal web api controller.
Notice in ASP.NET core MVC model binding, we MUST specify the binding source, like [FromBody]
, [FromHeader]
, [FromForm]
, [FromQuery]
, [FromRoute]
.
[Route("api/Basic/[controller]")]
public class CustomerController : BaseController
{
[HttpGet("GetAll")]
public IQueryable<Customer> GetAll()
{
throw new NotImplementedException();
}
[HttpGet("Get/{id}")]
public Customer Get(int id)
{
throw new NotImplementedException();
}
[HttpPost("Create")]
public async Task<HttpResponseMessage> Create([FromBody]Customer cust)
{
throw new NotImplementedException();
}
[HttpPut("Update")]
[CustomExceptionFilter]
public async Task<HttpResponseMessage> Update([FromBody]Customer cust)
{
throw new NotImplementedException();
}
[HttpDelete("Remove/{id}")]
[CustomExceptionFilter]
public async Task<HttpResponseMessage> Remove(int id)
{
throw new NotImplementedException();
}
}
Thaz all for Web Api, we will write the front-end in the next day.