插入/更新后获得内部服务器错误(500)作为响应

时间:2019-01-31 22:59:14

标签: asp.net entity-framework asp.net-core

CRUD操作在数据库上工作正常,但我在POST / PUT操作中收到500个内部服务器错误。 GET / DELETE我要200。

我在ASP.NET中使用crud操作,并且我的代码在prod中运行。我需要将其迁移到.NET Core。在测试过程中,我发现CRUD操作可以正常工作,并且可以看到与SQL数据库中的数据有关的更改,但是对于插入/更新,我得到500错误的响应。

.NET Framework的代码(工作中):-

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的代码(不起作用):-

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");
            }
        });
    }
}

我无法找到错误所在。您能帮我解决这个问题吗?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果您想像Web API一样返回GetActivityUpdates,请尝试在GetActivityUpdates方法上方定义路由名称。

[HttpGet("api/activityUpdates/GetActivityUpdates", Name = "GetActivityUpdates")]
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("GetActivityUpdates", activityUpdates);
}

答案 1 :(得分:0)

请尝试从您的post方法未创建的路线返回Ok(),并检查其是否正常工作。如果可行,则可能是您未在创建的路线中定义要使用的路线。