尝试在asp.net mvc中注册用户时出错



嗨,我在尝试注册时遇到了一个问题。这是我的代码:

public ActionResult RegisterButton(Models.Users User)
{
using (MyDbContext db = new MyDbContext())
{
if (ModelState.IsValid == false)
{
return View("Register", User);
}
else
{
db.Users.Add(User);
db.SaveChanges();
Session["UserId"] = User.Id;
//Directory.CreateDirectory(string.Format("~/App_Data/{0}",User.UserName+User.Id.ToString()));
return RedirectToAction("Profile", "Profile",new { User.Id});
}
}
}

这也是我的路线配置代码:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

我得到这个错误:参数字典包含不可为null的类型"System"的参数"UserId"的null条目。方法"System"的Int32"。网状物Mvc。"DigiDaroo中的ActionResult配置文件(Int32("。控制器。ProfileController’。可选参数必须是引用类型、可为null的类型,或者声明为可选参数

请帮助:|

根据您提供的代码,您的RegisterButton方法将向浏览器返回一个重定向响应,其位置标头值如下

/Profile/Profile/101

其中101被替换为新用户记录的实际ID。使用您的路由配置,如果您的操作方法参数名称为id,那么您的代码不会抛出错误消息。由于您收到了错误消息,我认为您的操作方法参数名称是其他名称。因此,请确保显式地传递routeValue对象。

例如,如果你的操作方法参数名称是userId,就像这个

public ActionResult Profile(int userId)
{
// to do : return something
}

你的重定向响应呼叫应该像这个

return RedirectToAction("Profile", "Profile",new { userId = User.Id});

这将把重定向响应的位置头值作为/Profile/Profile?userId=101发送,浏览器将使用它来发出GET请求。由于我们在querystring中显式传递userId参数,您的错误参数将正确地填充值101

另一个选项是将操作方法参数名称更改为id

public ActionResult Profile(int id)
{
// to do : return something
}

最新更新