插入/更新后响应出现内部服务器错误(500)

问题描述 投票:0回答:3

CRUD 操作在数据库中工作正常,但我在 POST/PUT 操作中收到 500 内部服务器错误。我因 GET/DELETE 而获得 200 美元。

我在 ASP.NET 中进行增删改查操作,我的代码在产品中运行。我需要将其迁移到 .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;
    }
}

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

我找不到错误在哪里。你能帮我解决这个问题吗?任何帮助将不胜感激。

asp.net entity-framework asp.net-core
3个回答
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);
}

0
投票

请尝试从未创建路由的 post 方法返回 Ok() 并检查它是否有效。如果它有效,那么可能是您没有定义在创建的路线中使用的路线。


0
投票

请尝试返回类似 return Ok() 的内容,并确保将 [HttpPost] 放在开头。

在此处获取 CRUD 参考 --> https://finwithtech.com/sql-server-authentication-authorization-net-7/

© www.soinside.com 2019 - 2024. All rights reserved.