简体   繁体   English

动态路径的ASP.NET MVC授权

[英]ASP.NET MVC Authorization for a dynamic path

I am using forms authentication with ASP.NET MVC. 我正在使用ASP.NET MVC进行表单身份验证。 Within web.config at application level I can set the paths that I require authentication to as follows; 在应用程序级别的web.config中,我可以将需要身份验证的路径设置如下:

<location path="subdir1">
<system.web>
    <authorization>
        <allow users ="?" />
    </authorization>
</system.web>
</location>

subdir1 is folder name within the Views folder. subdir1是“视图”文件夹中的文件夹名称。 This works for the web page routing as siteurl.com/subdir1 . 这适用于将网页路由为siteurl.com/subdir1

However, if my subdir1 is under another dynamically created route, this setting does not work. 但是,如果我的subdir1在另一个动态创建的路由下,则此设置不起作用。 For instance; 例如; siteurl.com/dynamic/subdir1 does not request authentication. siteurl.com/dynamic/subdir1不请求身份验证。 dynamic is created at runtime and web.config does not know about it at application start but it should not care about it, I just want it to ask for authentication whenever there is an access to subdir1 route. 动态是在运行时创建的,而web.config在应用程序启动时并不知道它,但它不关心它,我只希望它在有对subdir1路由的访问权时就要求身份验证。

Is there any way that I can set the location's path attribute for this case? 在这种情况下,有什么方法可以设置位置的path属性? or do you have any other way to solve this issue? 还是您有其他解决方法?

Any help would be appreciated. 任何帮助,将不胜感激。 cas sakal 卡萨萨卡尔

You can control authorization by using the Authorize attribute on the appropriate actions or controllers. 您可以通过在适当的操作或控制器上使用Authorize属性来控制授权。

[Authorize]
public ActionResult MyAction()
{
   //stuff
}

Some more information can be found at ASP.NET MVC Authorization 可以在ASP.NET MVC授权中找到更多信息。

You should be using the AuthorizeAttribute on your controllers/actions rather than setting up access in the web.config file for routes that map onto your controllers. 您应该在控制器/操作上使用AuthorizeAttribute ,而不是在web.config文件中为映射到控制器的路由设置访问权限。 You only need to apply the attribute to those actions (methods) that require authorization if not all of your actions require a logged in user. 如果并非所有动作都需要登录用户,则只需将属性应用于需要授权的动作(方法)。

[Authorize]
public class ProtectedController : Controller
{
    // all actions in this controller require the user to be logged in
}

public class MixedController : Controller
{
    [Authorize]
    public ActionResult ProtectedAction()
    {
        // this action requires the user to be logged in
    }

    public ActionResult PublicAction()
    {
       // this action is available to anonymous users
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM