开发者

ASP.NET MVC Authorization for a dynamic path

开发者 https://www.devze.com 2023-01-28 07:06 出处:网络
I am using forms authentication with ASP.NET MVC. Within web.config at application level I can set the paths that I require authentication to as follows;

I am using forms authentication with ASP.NET MVC. Within web.config at application level I can set the paths that I require authentication to as follows;

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

subdir1 is folder name within the Views folder. This works for the web page routing as siteurl.com/subdir1.

However, if my subdir1 is under another dynamically created route, this setting does not work. For instance; siteurl.com/dynamic/subdir1 does not request authentication. 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.

Is there any way that I can set the location's path attribute for this case? 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]
public ActionResult MyAction()
{
   //stuff
}

Some more information can be found at ASP.NET MVC Authorization


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. 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
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号