Sorry for the basic question.
From within the Global.asax
, I want to get the absolute path to a controller's action, like we get by calling Response.Redirect("~/subfolder")
from anywhere or by calling @Url.Content("~/controller/action")
from within our views.
In my Global.asax events, I'd like to do something like this:
protected void Application_BeginRequest(object sender, EventArgs args)
{
if ( string.Compare(HttpContext.Current.Request.RawUrl, "~/foo", true) == 0 )
// do something
// I'd like the "~foo" to resolve to the virtual path relative to
// the application root
}
Here is the answer for your problem
You can simply get the controller and action name like this
protected void Application_BeginRequest(object sender, EventArgs args)
{
HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
RouteData routeData = urlHelper.RouteCollection.GetRouteData(currentContext);
string action = routeData.Values["action"] as string;
string controller = routeData.Values["controller"] as string;
if (string.Compare(controller, "foo", true) == 0)
// do something
// if the controller for current request if foo
}
void Session_Start(object sender, EventArgs e)
{
if (Session.IsNewSession && Session["SessionExpire"] == null)
{
//Your code
}
}
You have many options to do this. But I will not recommend to use Global.asax
place to do such comparisons
This is also very important approach. You can use HttpModule
.
Base Controller class
You can apply the Action Filter to an entire Controller class like below
namespace MvcApplication1.Controllers
{
[MyActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
}
Whenever any of the actions exposed by the Home controller are invoked – either the Index() method or the About() method, the Action Filter class will execute first.
namespace MvcApplication1.ActionFilters
{
public class MyActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Your code for comparison
}
}
}
If you pay attention to the above code, the OnActionExecuting will execute before executing the Action Method
Using this approach will execute the OnActionExecuting
for Index method only.
namespace MvcApplication1.Controllers
{
public class DataController : Controller
{
[MyActionFilter]
public string Index()
{
//Your code for comparison
}
}
}
RouteData.Values["controller"] //to get the current Controller Name
RouteData.Values["action"] //to get the current action Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With