hi I am newbie in asp.net Core 2.0 web Api. I was unable to find out the problems after many hours of trying. Please help.
I have successfully created a Sql Server Database with Code First approach but I encountered some problem in doing CRUD with Web Api thru PostMan.
----A) Creating a Database with Code First approach
1) This is my appsettings.json
"connectionstrings": {
"Default": "Server = .\\SQL2017Express; Database = ContactDB; Integrated Security = True;"
},
2) in startUp class
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ContactContext>(option => option.UseSqlServer (Configuration.GetConnectionString("Default")));
}
------- B) using DbContext and Model and repository approach
1) DbContext
using aspCoreWebApiUserDb.Models;
using Microsoft.EntityFrameworkCore;
namespace aspCoreWebApiUserDb.DataContext
{
public class ContactContext : DbContext
{
public ContactContext(DbContextOptions<ContactContext> options)
: base(options) { }
public ContactContext() { }
public DbSet<Contacts> Contacts { get; set; }
}
}
2) Model
public class Contacts
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobilePhone { get; set; }
}
3) using IContactRepository and ContactRepository
public interface IContactRepository
{
Task Add(Contacts item);
Task<IEnumerable<Contacts>> GetAll();
Task<Contacts> Find(string key);
Task Remove(string Id);
Task Update(Contacts item);
bool CheckValidUserKey(string reqkey);
}
using Microsoft.EntityFrameworkCore;
using aspCoreWebApiUserDb.Models;
using aspCoreWebApiUserDb.DataContext;
namespace aspCoreWebApiUserDb.DataLayerRepository
{
public class ContactRepository : IContactRepository
{
ContactContext _context;
public ContactRepository(ContactContext context)
{
_context = context;
}
public async Task Add(Contacts item)
{
await _context.Contacts.AddAsync(item);
await _context.SaveChangesAsync();
}
public async Task<IEnumerable<Contacts>> GetAll()
{
return await _context.Contacts.ToListAsync();
}
public bool CheckValidUserKey(string reqkey)
{
var userkeyList = new List<string>
{
"28236d8ec201df516d0f6472d516d72d",
"38236d8ec201df516d0f6472d516d72c",
"48236d8ec201df516d0f6472d516d72b"
};
if (userkeyList.Contains(reqkey))
{
return true;
}
else
{
return false;
}
}
public async Task<Contacts> Find(string key)
{
return await _context.Contacts
.Where(e => e.MobilePhone.Equals(key))
.SingleOrDefaultAsync();
}
public async Task Remove(string Id)
{
var itemToRemove = await _context.Contacts.SingleOrDefaultAsync(r => r.MobilePhone == Id);
if (itemToRemove != null)
{
_context.Contacts.Remove(itemToRemove);
await _context.SaveChangesAsync();
}
}
public async Task Update(Contacts item)
{
var itemToUpdate = await _context.Contacts.SingleOrDefaultAsync(r => r.MobilePhone == item.MobilePhone);
if (itemToUpdate != null)
{
itemToUpdate.FirstName = item.FirstName;
itemToUpdate.LastName = item.LastName;
itemToUpdate.MobilePhone = item.MobilePhone;
await _context.SaveChangesAsync();
}
}
}
}
--- 4) create a ContactController
using aspCoreWebApiUserDb.Models;
using aspCoreWebApiUserDb.DataContext;
using aspCoreWebApiUserDb.DataLayerRepository;
namespace aspCoreWebApiUserDb.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class ContactsController : Controller
{
public IContactRepository ContactsRepo { get; set; }
public ContactsController(IContactRepository _repo)
{
ContactsRepo = _repo;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var contactList = await ContactsRepo.GetAll();
return Ok(contactList);
}
[HttpGet("{id}", Name = "GetContacts")]
public async Task<IActionResult> GetById(string id)
{
var item = await ContactsRepo.Find(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
[HttpPost]
public async Task<IActionResult> Create([FromBody] Contacts item)
{
if (item == null)
{
return BadRequest();
}
await ContactsRepo.Add(item);
return CreatedAtRoute("GetContacts", new { Controller = "Contacts", id = item.MobilePhone }, item);
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(string id, [FromBody] Contacts item)
{
if (item == null)
{
return BadRequest();
}
var contactObj = await ContactsRepo.Find(id);
if (contactObj == null)
{
return NotFound();
}
await ContactsRepo.Update(item);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
await ContactsRepo.Remove(id);
return NoContent();
}
}
}
Deploy this Web api app to IIS ( Local Machine):
This project has no compilation error, it was build successfully. I have also successfully deployed this Asp.net Core 2.0 WebApi to local Machine IIS.
----testing Check:
a) Note: have checked that SQL Server 2017 is running in Services under Control panel
b) Have tested the Default ValuesController in the WebApi Template
I was able to get the values with Get : http://192.168.1.8:8989/api/values
c) I have manually create some data in the table using SSMS for SQL Server 2017
here the problems when using Postman to do CRUD. (All app are in this PC (Local machine): Postman and IIS).
1) do a Post with Postman
Post : http://192.168.1.8:8989/api/contacts
Json Data for the Body in PostMan:
{
"FirstName" : "John",
"LastName" : "David",
"MobilePhone" : "123456789"
}
problem : status 500 internal server Error
2) Do a get with PostMan
GET : http://192.168.1.8:8989/api/contacts
Problem: status 500 internal server Error
What seems to be the problem? I need your help. Thanks