【问题标题】:Error 404 on page after adding new code in controller在控制器中添加新代码后页面出现错误 404
【发布时间】:2019-12-14 04:08:12
【问题描述】:

我为带有视图的新模型添加了一个新控制器,默认情况下一切正常,但是当我添加一些代码时,它破坏了页面,现在当我尝试打开它时,我收到错误 404。 如果我删除该代码,我仍然会收到错误消息,并且无法恢复默认值。

我在另一个控制器上尝试了同样的事情,得到了同样的效果。

我尝试使用实体框架创建控制器,但结果相同。

我的其他控制器可以正常显示数据,但使用此控制器在数据库中创建数据不起作用。

不起作用的控制器:

public class AccessController : Controller
{
    private readonly DataAccess data;


    public AccessController(DataAccess data)
    {
        this.data = data;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(AccessModel model)
    {
        if (ModelState.IsValid)
        {
            var CurrentUserName = this.User.FindFirstValue(ClaimTypes.Name);
            List<ApplicationUser> users = new List<ApplicationUser>();
            var userData = data.LoadUser();
            string userID = null;

            foreach (var row in userData)
            {
                users.Add(new ApplicationUser
                {
                    MachineId = row.MachineId,
                    Email = row.Email
                });
            }

            for (int j = 0; j < users.Count; j++)
            {
                if (users[j].Email == CurrentUserName)
                    userID = users[j].MachineId;
            }

            AccessProcessor.CreateAccess(userID, model.OpenValve, model.OpenTrap,
                model.OpenFeedingPen, model.StartMachine, data);
        }
        return View();
    }

}

启动时配置:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

appsettings.json:

"ConnectionStrings": {
"MVCCoreAppDB": "The connection string"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
"AllowedHosts": "*"

【问题讨论】:

    标签: c# model-view-controller http-status-code-404 asp.net-core-2.2


    【解决方案1】:

    这是因为你用HttpPost 装饰了你的Create 操作。您收到 404 错误的原因是因为您没有用作 GetCreate 操作。您所要做的就是添加另一个动作:

    public ActionResult Create()
    {
       var model = new AccessModel();
       return View(model);
    }
    

    【讨论】:

    • Errff 太简单了...非常感谢。我现在对控制器的工作原理有了一些了解。
    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2012-02-23
    • 2022-12-09
    相关资源
    最近更新 更多