【发布时间】:2018-04-15 12:43:58
【问题描述】:
我刚刚开始使用 asp.net Core 2.0 web api。请提供您的帮助。
我已成功将 asp.net WebApi 应用程序部署到本地 IIS 和 我用下面的代码在 Sql Server 2017(免费版)中创建了一个数据库。
问题:当我使用 PostMan 发帖时出现状态 500 内部服务器错误
1) in StartUp.cs with ConnectionString:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ContactContext>(option => option.UseSqlServer(Configuration.GetConnectionString("Default")));
}
2) connection string in appsettings.json
"connectionstrings": {
"Default": "Server = .\\SQL2017Express; Database = ContactDB; Integrated Security = True;"
}
**The Problems Encountered:**
problem: status 500 internal server error when I 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"
}
// controller
[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();
}
}
这两种连接字符串我都试过了:
a)
"connectionstrings": {
"Default": "Server = .\\SQL2017Express; Database = ContactDB; Integrated Security = True;"
},
b)
"connectionstrings": {
"Default": "Server = .\\SQL2017Express; Database = ContactDB; User Id=sa; Password=xxxxx ; Integrated Security = True;"
},
【问题讨论】:
标签: asp.net-core-2.0 asp.net-core-webapi