authorization in MVC project

2019-05-18 18:38发布

问题:

I have login page in MVC project and i created authorization config this.

  <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880"  defaultUrl="~/Home/Index"/>
    </authentication>

  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>

How can i access in register page?

回答1:

Depending on what version of MVC you're using the common practice I see now in MVC3/4 is to instead of restricting access to specific actions, to restrict access to all actions, by adding Authorize() as a global filter and then grant access to a few select actions using the AllowAnonymous() attribute to act as a white-list of actions that do not need to be protected. (Like Login, Register, etc).

global.asax

protected void Application_Start()
{
    filters.Add(new AuthorizeAttribute());
}

AccountsController.cs

[AllowAnonymous]
public ActionResult Login()
{
    //Perform login...
}

Then you're web.config just has this

<authorization>
    <allow users="*" />
</authorization>


回答2:

By default you should go to Register() action method of Account controller

// GET: /Account/Register

According to your web.config: try to add this to web.config before <system.web> tag.

 <location allowOverride="true" path="Account/Register">
    <system.web>
      <authorization>
        <allow users="?" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>