CRUD操作与数据库工作正常,但我得到了500内部服务器错误的POST/PUT操作。我得到了200的GET/POST。
我在ASP.NET中使用crud操作,我的代码在prod中运行。我需要将其迁移到.NET Core。在测试时,我发现CRUD操作工作正常,我可以看到与SQL数据库内数据相关的更改,但对于插入/更新,我得到500错误响应。
.NET Framework(Working):-
public class ActivityUpdatesController : ApiController
{
private PortfolioMgmtEntities db = new PortfolioMgmtEntities();
// GET: api/ActivityUpdates
public IQueryable<ActivityUpdate> GetActivityUpdates()
{
return db.ActivityUpdates;
}
[Route("api/activityUpdates/getByProjectId")]
public IQueryable<ActivityUpdate> getActivityUpdatesByProjectId(int projectId)
{
IQueryable<ActivityUpdate> activityUpdates = from r in db.ActivityUpdates
where r.ProjectID == projectId
select r;
return activityUpdates;
}
// GET: api/ActivityUpdates/5
[ResponseType(typeof(ActivityUpdate))]
public IHttpActionResult GetActivityUpdate(int id)
{
ActivityUpdate activityUpdate = db.ActivityUpdates.Find(id);
if (activityUpdate == null)
{
return NotFound();
}
return Ok(activityUpdate);
}
// PUT: api/ActivityUpdates/5
[ResponseType(typeof(void))]
public IHttpActionResult PutActivityUpdate(int id, ActivityUpdate activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != activityUpdate.RecordID)
{
return BadRequest();
}
db.Entry(activityUpdate).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ActivityUpdateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/ActivityUpdates
[ResponseType(typeof(ActivityUpdate))]
[Route("api/activityUpdates/create")]
public IHttpActionResult PostActivityUpdate(int projectId, [FromBody] ActivityUpdate activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
activityUpdate.ProjectID = projectId;
activityUpdate.UpdatedDate = DateTime.Now;
db.ActivityUpdates.Add(activityUpdate);
db.SaveChanges();
IQueryable<ActivityUpdate> activityUpdates = from au in db.ActivityUpdates
where au.ProjectID == projectId
select au;
return CreatedAtRoute("DefaultApi", new { controller = "ActivityUpdates" }, activityUpdates);
}
// DELETE: api/ActivityUpdates/5
[ResponseType(typeof(ActivityUpdate))]
public IHttpActionResult DeleteActivityUpdate(int id)
{
ActivityUpdate activityUpdate = db.ActivityUpdates.Find(id);
if (activityUpdate == null)
{
return NotFound();
}
db.ActivityUpdates.Remove(activityUpdate);
db.SaveChanges();
return Ok(activityUpdate);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ActivityUpdateExists(int id)
{
return db.ActivityUpdates.Count(e => e.RecordID == id) > 0;
}
}
字符串
WebAPiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableCors(new EnableCorsAttribute("*", "*", "GET,PUT,POST,DELETE"));
}
型
.NET Core(Not Working):-
public class ActivityUpdatesController : Controller
{
private aeportfoliomgmtdbContext db = new aeportfoliomgmtdbContext();
// GET: api/ActivityUpdates
public IQueryable<ActivityUpdates> GetActivityUpdates()
{
return db.ActivityUpdates;
}
[HttpGet]
[Route("api/activityUpdates/getByProjectId")]
public IQueryable<ActivityUpdates> getActivityUpdatesByProjectId(int projectId)
{
IQueryable<ActivityUpdates> activityUpdates = from r in db.ActivityUpdates
where r.ProjectId == projectId
select r;
return activityUpdates;
}
[HttpPost]
[Route("api/activityUpdates/create")]
public IActionResult PostActivityUpdate(int projectId, [FromBody] ActivityUpdates activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
activityUpdate.ProjectId = projectId;
activityUpdate.UpdatedDate = DateTime.Now;
db.ActivityUpdates.Add(activityUpdate);
db.SaveChanges();
IQueryable<ActivityUpdates> activityUpdates = from au in db.ActivityUpdates
where au.ProjectId == projectId
select au;
return CreatedAtRoute("DefaultApi", new { controller = "ActivityUpdates" }, activityUpdates);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ActivityUpdateExists(int id)
{
return db.ActivityUpdates.Count(e => e.RecordId == id) > 0;
}
}
型
startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseCors("CorsPolicy");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "DefaultApi",
template: "api/{controller}/{id}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
型
我找不到错误的地方。你能帮我解决这个问题吗?任何帮助都将不胜感激。
3条答案
按热度按时间gojuced71#
如果你想像web API一样返回
GetActivityUpdates
,试着在GetActivityUpdates
方法上面定义路由名。字符串
vzgqcmou2#
请尝试返回类似return Ok()的东西,同时确保您在开始时输入[HttpPost]。
在此处获取CRUD引用--> https://finwithtech.com/sql-server-authentication-authorization-net-7/
cnh2zyt33#
请尝试从你的post方法返回Ok()not created route,并检查它是否工作。如果它工作,那么可能是你没有定义你在创建的路由中使用的路由。