Getting the Current controller and action sent to the Route

冷暖自知 提交于 2019-12-12 01:27:13

问题


I am attempting to Get the current controller and action being called in the route. In my Global.asax.cs I have the following using and the following line:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using IProwlAdminUI.Models;

*** LINE WITH ISSUE***
string action = ViewContext.RouteData.Values["controller"].ToString() + ViewContext.RouteData.Values["action"].ToString()
*******

Right now the ViewContext.RouteData is giving me "an object reference is required for the non-static field, method, or property 'System.Web.Mvc.ControllerContext.RouteData.Get'"

I need to get this so that I can use the controller and action to evaluate permissions for the user and see if they can perform the action they are attempting to do.

Any Help on this would be greatly appreciated.

Thanks


回答1:


You cannot do what you are trying to do because the code in Global.asax executes only once when your application starts up. This happens before the context of an incoming request is available and that is why you cannot access the RouteData values.

On a more general note, you can write a custom AuthorizationAttribute to do what you want. See the following link for an example: http://davidhayden.com/blog/dave/archive/2009/04/09/CustomAuthorizationASPNETMVCFrameworkAuthorizeAttribute.aspx



来源:https://stackoverflow.com/questions/3258503/getting-the-current-controller-and-action-sent-to-the-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!