0 Replies - 5835 Views - Last Post: 30 October 2011 - 12:10 AM

#1 litedrive  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 102
  • Joined: 30-September 10

MVC3 Register Action Not Found

Posted 30 October 2011 - 12:10 AM

I get a 404 error when I try to use my Register() action.

In a nutshell the url path is ~/Controllers/Account/Register(), or localhost/Account/Register rather.

I'm well aware that by default, ASP.net MVC 3 comes with a pre-installed registration module. The thing, however, is that I felt as though it would be necessary to add a few modifications for what I need to do. I think the problem MIGHT have something to do with my Views Web.config file (and possibly my root Web.config file?). Because of this, I'll post my config files as well.

Here's my Account/Register.cshtml view


@model CmsNew.Models.RegisterModel

@{
    ViewBag.Title = "Register";
}

<h2>Welcome! Enter the account Registration page. This is where the magic is just about to begin.</h2>
<p>
    Use the form below to create a new account. 
</p>
<p>
    Passwords are required to be a minimum of @Membership.MinRequiredPasswordLength characters in length.
</p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    @Html.ValidationSummary(true, "Account creation was unsuccessful. You probably didn't enter your information correctly: please correct the errors and try again.")
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.Email)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Email)
                @Html.ValidationMessageFor(m => m.Email, "Please enter a valid email address.")
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.Username)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Username)
                @Html.ValidationMessageFor(m => m.Username, "Oops! Sorry, that Username is already taken; please try a different username.")
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password, "Please enter a valid password - one which has at least one uppercase letter, one lowercase letter, and a number.")
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.ConfirmPassword)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.ConfirmPassword)
                @Html.ValidationMessageFor(m => m.ConfirmPassword, "Passwords do not match.")
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.FirstName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.FirstName)
                @Html.ValidationMessageFor(m => m.FirstName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.LastName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.LastName)
                @Html.ValidationMessageFor(m => m.LastName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.ConfirmPassword)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.ConfirmPassword)
                @Html.ValidationMessageFor(m => m.ConfirmPassword)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.AddressOne)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.AddressOne)
                @Html.ValidationMessageFor(m => m.AddressOne)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.AddressTwo)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.AddressTwo)
                @Html.ValidationMessageFor(m => m.AddressTwo)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.City)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.City)
                @Html.ValidationMessageFor(m => m.City)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.StateProvince)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.StateProvince)
                @Html.ValidationMessageFor(m => m.StateProvince)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.Country)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Country)
                @Html.ValidationMessageFor(m => m.Country)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.Zipcode)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Zipcode)
                @Html.ValidationMessageFor(m => m.Zipcode)
            </div>

            <p>
                <input type="submit" value="Register" />
            </p>
        </fieldset>
    </div>
}


And my AccountController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;


using CmsNew.Models;
using CmsNew.Models.Security;

namespace CmsNew.Controllers
{
    public class AccountController : Controller
    {
        public AccountDataModel UserData { get { return this.userData; } }
        
        private AccountDataModel userData;

        private bool isLoggedIn = false;

        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Account/LogIn

        public ActionResult LogIn(LogInModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {

                bool userExists = UserConfig.CheckIfUserExists(model.Email);
                bool userValidated = UserConfig.ValidateUser("main_account", model.Email, model.Password);

                if (userValidated && userExists)
                {
                    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                    this.userData = CreateAccountData(model.Email);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        Redirect(returnUrl);
                    }
                }
                else
                {
                    return RedirectToAction("Index", returnUrl);
                }

               
                
            }
           
            return View();
        }

        //
        // POST: /Account/LogOut

        [HttpPost]
        public ActionResult LogOut()
        {
            this.isLoggedIn = false;
            FormsAuthentication.SignOut();

            ViewData["Message"] = Server.HtmlEncode("You are now signed out.");

            this.userData = null;

            return RedirectToAction("Index", "Home", ViewData);
        }

        //
        // POST: /Account/Register
        
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            bool success = UserConfig.CreateAccount(model);

            if (!success)
                throw new Exception("There was an error in registering you as a user. Please contact the server administrator for further information.");

            return View(model);
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "UserModel name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The passwordValue provided is invalid. Please enter a valid passwordValue value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The passwordValue retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The passwordValue retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        #region AccountModifiers
        public static AccountDataModel CreateAccountData(string email)
        { 
            Database db = DatabaseSchemas.CmsMain;
            string table = "main_account";

            AccountDataModel adm = new AccountDataModel
            {
                AccountID = (int)UserConfig.FetchUserData(table, "account_id", email, db),
                AddressTwo = (string)UserConfig.FetchUserData(table, "address_two", email, db),
                AddressOne = (string)UserConfig.FetchUserData(table, "address_one", email, db),
                BannedID = (int)UserConfig.FetchUserData(table, "banned_id", email, db),
                City = (string)UserConfig.FetchUserData(table, "city", email, db),
                Country = (string)UserConfig.FetchUserData(table, "country", email, db),
                Email = (string)UserConfig.FetchUserData(table, "email", email, db),
                FirstName = (string)UserConfig.FetchUserData(table, "first_name", email, db),
                LastName = (string)UserConfig.FetchUserData(table, "last_name", email, db),
                Password = (string)UserConfig.FetchUserData(table, "password", email, db),
                StateProvince = (string)UserConfig.FetchUserData(table, "state/province", email, db),
                UserID = (int)UserConfig.FetchUserData(table, "user_id", email, db),
                Username = (string)UserConfig.FetchUserData(table, "username", email, db),
                ZipCode = (string)UserConfig.FetchUserData(table, "zipcode", email, db)
            };

            return adm;
        }

        private ActionResult ValidateUser(LogInModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Email, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("IncorrectPassword", "The user name or password provided is incorrect.");
                }
            }

            return RedirectToAction("Index", "Home");
        }

        private void RememberUser()
        {
            ViewData["Email"] = StringEncryptor.DecryptStringAES(this.userData.Email, SharedSecretModel.SecretEmail);
            ViewData["Password"] = StringEncryptor.DecryptStringAES(this.userData.Password, SharedSecretModel.SecretPassword);
        }

        #endregion
    }
}



My ROOT Web.config file

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavascriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <httpRuntime relaxedUrlToFileSystemMapping="true" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
    <httpErrors errorMode="Custom">
      <!-- Catch 404 due to IIS request filtering (e.g. bin, web.config, app_code, app_globalresources, app_localresources, app_webreferences, app_data, app_browsers) -->
      <error statusCode="404" subStatusCode="8" path="/notfound" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>



...As well as my VIEWS Web.config file

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>


  <system.web>
    <httpHandlers>
        <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>
         
    

    <!--  
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>



I've been spending all night trying to figure this one out. Initially, I thought it may be a server issue, but I'm realizing now that it could just be the fact that I changed quite a bit of what was given to me by default.

Thanks for the help.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1