我开始用c#开发API,以便通过Azure访问在线SQL服务器上的数据。 当我在localhost中运行Web API时,一切正常,但是当我发布它时,我的api /雇员却无法在localhost中正常工作。 我得到的错误是“ 500(内部服务器错误)” 请帮我,我在互联网上搜索过,但是找不到可以帮助我的东西。
有我的connectionString:
<add name="groupea07Entities1" connectionString="metadata=res://*/Models.Employee.csdl|res://*/Models.Employee.ssdl|res://*/Models.Employee.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:groupea07.database.windows.net,1433;Initial Catalog=groupea07;Persist Security Info=False;User ID=MyUser;Password=MyPwd;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
有我的EmployeesController:
public class EmployeesController : ApiController
{
private groupea07Entities1 db = new groupea07Entities1();
// GET: api/Employees
public IQueryable<Employee> GetEmployees()
{
return db.Employee;
}
// PUT: api/Employees/5
public HttpResponseMessage PutEmployee(Employee employee)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
db.Entry(employee).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// POST: api/Employees
public HttpResponseMessage PostEmployee(Employee employee)
{
if (!ModelState.IsValid)
{
db.Employee.Add(employee);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, employee);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = employee.EmployeeID }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// DELETE: api/Employees/5
public HttpResponseMessage DeleteEmployee(Employee employee)
{
Employee remove_employee = db.Employee.Find(employee.EmployeeID);
if (remove_employee == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Employee.Remove(remove_employee);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool EmployeeExists(int id)
{
return db.Employee.Count(e => e.EmployeeID == id) > 0;
}
}
答案 0 :(得分:-1)
错误500是通用错误代码,只要您的webSite / webApi中发生异常,您都将得到它,因此它不会提供有关错误的详细信息。
但是,您的屏幕快照显示该异常是System.InvalidOperationException,更重要的是,引起该异常的innerException是EntityFramework尝试打开数据库The underlying provider failed on Open
上的连接的失败尝试。
这可能有多种原因。
大多数时候,在Internet上搜索有关异常的描述(此处为The underlying provider failed on Open
)很有帮助。
还有其他可能导致此特殊异常的原因: https://stackoverflow.com/a/3081776/3608483