Getting Route Values in Controller
-
Hi, I have the following Route Contex:
context.MapRoute(
"Space_default",
"Space/{Value}/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);And I would like to get {Value} in my controller in the following code:
public class OverviewController : Controller { string myValue = (int)RouteData.Values\["Value"\]; \[CourseAccess(CourseId = myValue)\] public ActionResult Index(int CourseId) {...
I was wondering how can I do that and use that value before my actions. Thank you.
-
Hi, I have the following Route Contex:
context.MapRoute(
"Space_default",
"Space/{Value}/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);And I would like to get {Value} in my controller in the following code:
public class OverviewController : Controller { string myValue = (int)RouteData.Values\["Value"\]; \[CourseAccess(CourseId = myValue)\] public ActionResult Index(int CourseId) {...
I was wondering how can I do that and use that value before my actions. Thank you.
You can't use a field or local variable in an attribute. The attribute parameters and properties are compiled into your code, so they can't depend on runtime data. You'll probably need to look at using a filter attribute: Understanding Action Filters (C#) | Microsoft Docs[^]
public sealed class CourseAccessAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
int courseId = (int)filterContext.RouteData["Value"];
if (!HasAccessToCourse(filterContext, courseId))
{
filterContext.Result = new HttpUnauthorizedResult();
}
}private bool HasAccessToCourse(AuthorizationContext filterContext, int courseId) { ... }
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
You can't use a field or local variable in an attribute. The attribute parameters and properties are compiled into your code, so they can't depend on runtime data. You'll probably need to look at using a filter attribute: Understanding Action Filters (C#) | Microsoft Docs[^]
public sealed class CourseAccessAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
int courseId = (int)filterContext.RouteData["Value"];
if (!HasAccessToCourse(filterContext, courseId))
{
filterContext.Result = new HttpUnauthorizedResult();
}
}private bool HasAccessToCourse(AuthorizationContext filterContext, int courseId) { ... }
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
Nice! Thank you! :)