如何修复500个内部



我已经为学生构建了在线测试系统,但是我无法通过JSON通过答案。我遇到了500个内部错误,我无法弄清楚如何修复。

我试图删除很长的JSON数据,但这无济于事,我无法理解问题所在。一切都传递到控制器,直到db.name.add(item(;然后它返回500个内部错误

<script>
    $("#save_value").click(function(event){
        event.preventDefault();
        jsonObj = [];
        $("input:radio:checked").each(function() {
            var question_id = $(this).attr("data-value");
            var selection = $(this).val();
            item = {}
            item ["selection"] = selection;
            item ["question_id"] = question_id;
            jsonObj.push(item);
        });
        jsonString = JSON.stringify(jsonObj);
        var form = $('#FormId').val();
        var stu = $('#StudentId').val();
        var note = $('#notes').val();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("SaveForm", "Home")',
            data:  JSON.stringify({'FormId': form , 'StudentId' : stu , 'notes' : note , 'data' : jsonString }),
            success: function(result) {
                console.log('Data received: ');
                console.log(result);
            },
        });
    })
</script>

控制器:

[HttpPost("SaveForm")]
public async Task<IActionResult> SaveForm([FromBody]FromAnswerModel model)
{
    if (model != null)
    {
        var id = int.Parse(User.Identity.Name);
        var member = _context.ClassesStudent.FirstOrDefault(m => m.Id == id);
        int years = 0;
        int months = 0;
        int days = 0;
        DateTime temp = member.BirthDate.Value;
        while (temp.AddYears(1) <= DateTime.Now)
        {
            temp = temp.AddYears(1);
            years++;
        }
        // get months
        while (temp.AddMonths(1) <= DateTime.Now)
        {
            temp = temp.AddMonths(1);
            months++;
        }
        // get days
        while (temp.AddDays(1) <= DateTime.Now)
        {
            temp = temp.AddDays(1);
            days++;
        }
        short positive = 0;
        short negative = 0;
        JArray a = JArray.Parse(model.data);
        foreach (JObject o in a.Children<JObject>())
        {
            foreach (JProperty p in o.Properties())
            {
                string name = p.Name;
                string value = (string)p.Value;
                Console.WriteLine(name + " -- " + value);
                if (value == "A")
                {
                    positive++;
                }
                else if(value =="B")
                {
                    negative++;
                }
            }
        }
        if(negative == 0)
        {
            int sum;
            if(years == 1)
            {
                years = 12;
                sum = years + months;
            }
            else
            {
                years = 12;
                int newMonths = 12 * years;
                sum = months + newMonths;
            }
            var item = new BoxesStudentobservationforms
            {
                Data = model.data,
                SavedDate = DateTime.UtcNow,
                IsCompleted = 1,
                FormId = model.FormId,
                StudentId = model.StudentId,
                Notes = model.notes,
                PositivePoints = positive,
                ImmortalPoints = negative,
                MonthlyWhenSave = (short)sum,
                Result = "Do not support."
            };
            _context.BoxesStudentobservationforms.Add(item);
            await _context.SaveChangesAsync();
        }
        else
        {
            int sum;
            if (years == 1)
            {
                years = 12;
                sum = years + months;
            }
            else
            {
                years = 12;
                int newMonths = 12 * years;
                sum = months + newMonths;
            }
            var item = new BoxesStudentobservationforms
            {
                Data = model.data,
                SavedDate = DateTime.UtcNow,
                IsCompleted = 1,
                FormId = model.FormId,
                StudentId = model.StudentId,
                Notes = model.notes,
                PositivePoints = positive,
                ImmortalPoints = negative,
                MonthlyWhenSave = (short)sum,
                Result = "support"
            };
            _context.BoxesStudentobservationforms.Add(item);
            await _context.SaveChangesAsync();
        }
        return Json("Success");
    }
    return Json("Success.");
}

它不能保存。正如我说的那部分

_context.BoxesStudentobservationforms.Add(item);
await _context.SaveChangesAsync();

然后返回500 intenval error。它在工作,但突然停止在本地和服务器上工作。

输出:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST https://localhost:5001/SaveForm application/json; charset=UTF-8 733
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "SaveForm", controller = "Home"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] SaveForm(BuyukAile.ViewModels.FromAnswerModel) on controller BuyukAile.Controllers.HomeController (BuyukAile).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization was successful.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method BuyukAile.Controllers.HomeController.SaveForm (BuyukAile) - Validation state: Valid
Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action BuyukAile.Controllers.HomeController.SaveForm (BuyukAile) in 118.6163ms
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> MySql.Data.MySqlClient.MySqlException: Cannot add or update a child row: a foreign key constraint fails (`buyukaile`.`boxes_studentobservationforms`, CONSTRAINT `boxes_studentobserva_form_id_3b194fa5_fk_boxes_obs` FOREIGN KEY (`form_id`) REFERENCES `boxes_observationform` (`id`))
   at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
   at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at BuyukAile.Controllers.HomeController.SaveForm(FromAnswerModel model) in C:UsersjackaOneDriveDesktopBA EĞİTİMBuyukAileControllersHomeController.cs:line 391
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 133.8998ms 500 text/html; charset=utf-8
 public partial class BoxesStudentobservationforms
    {
        public int Id { get; set; }
        public short MonthlyWhenSave { get; set; }
        public string Notes { get; set; }
        public DateTime? SavedDate { get; set; }
        public short PositivePoints { get; set; }
        public short ImmortalPoints { get; set; }
        public string Result { get; set; }
        public byte IsCompleted { get; set; }
        public string Data { get; set; }
        public int FormId { get; set; }
        public int? StudentId { get; set; }
        public BoxesObservationform Form { get; set; }
        public ClassesStudent Student { get; set; }
    }

您的500页说,您的mysql db上有一个错误,它与外键相关(formid&lt; -> formobservationid(。

可能的问题:您正在尝试错误的外国密钥或数据库用户与捕集相关的问题等...

我建议您创建一个临时页面,该页面写入屏幕精确的SQL命令,该命令引发此500页错误。

然后复制该SQL,然后尝试在您的MySQL db(通过Heidisql或MySqladmin(执行。

并检查结果。如果再次引发错误,请尝试在数据库侧求解。

,请通过更新您的问题与我们分享结果。

也请检查此问题:

相关问题1

相关问题2

最新更新