I have to make custom route but I stuck on a problem. That is my route
routes.MapRoute(
name: "IndexByUserName",
url: "{controller}/{action}/{username}",
defaults: new { controller = "Profile", action = "Edit", username = UrlParameter.Optional }
);
And when I go to url .../Profile/Edit/UserTest
for example I get 404 Not Found error, because my parameter username
is null
. My action looks like this
[Authorize]
[HttpGet]
public ActionResult Edit(string username)
{
ApplicationUser profile = db.Users.Find(username);
if (profile == null)
{
return HttpNotFound();
}
return View(profile);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id, Nickname, FirstName, LastName, SecondName, City, Address, Description, Skype, TelephoneNum")] ApplicationUser profile)
{
if (ModelState.IsValid)
{
var user = db.Users.Find(profile.Id);
if (user == null)
{
return HttpNotFound();
}
user.UserName = User.Identity.GetUserName();
user.FirstName = profile.FirstName;
user.SecondName = profile.SecondName;
user.LastName = profile.LastName;
user.SocialNetworks = profile.SocialNetworks;
user.Address = profile.Address;
user.City = profile.City;
user.TelephoneNum = profile.TelephoneNum;
user.Description = profile.Description;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return Redirect("/Profile/Index/" + User.Identity.Name);
}
return View(profile);
}
I don't know where the problem.