I am wondering if I can do something like RoutePrefix("{projectName}/usergroups")
because I have many projects and each project contains usergroups. Now in every Usergroup
controller I will first need to get the Project
that it's tied to. Is this possible?
I tried simply to do RoutePrefix("projects/{projectName}")
and then pass it in controller constructor but it does not work like that. I also tried to use Route
instead of RoutePrefix
on controller level but then my routes inside do not work.
[RoutePrefix("projects"), Authorization]
public class UsergroupController : Controller
{
private readonly Project _project; // i would like to inject it here on constructor
private readonly Account _account;
private readonly IProjectRepository _projectRepository;
public UsergroupController(IAuthorizationService auth, IProjectRepository projectRepository)
{
_projectRepository = projectRepository;
_account = auth.GetCurrentAccount();
}
[Route("{projectName}/usergroups"), HttpGet]
public ActionResult Index(string projectName)
{
// the problem that i will need to pass projectName
// to every action and do this check in every action as well
//
// looks like totally ugly code-duplication
var project = _projectRepository
.GetByAccountId(_account.Id.ToString())
.SingleOrDefault(x => x.Name == projectName);
if (project == null)
{
return HttpNotFound();
}
// now get all usergroups in this project e.g. project.Usergroups
return null;
}
}
As you can see, the description for Route mentions exposing the action(s), but RoutePrefix does not.
To override the RoutePrefix we need to use the ~ (tilde) symbol as shown below. With the above change, now the GetTeachers() action method is mapped to URI “/tech/teachers” as expected.
As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources. The earlier style of routing, called convention-based routing, is still fully supported.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
You can have a route prefix that takes parameters, but your action methods still have to accept the parameter just as if it was part of their route. You can't satisfy the dependency from the constructor of your controller:
[RoutePrefix("{projectName}/usergroups")]
public class UsergroupController : Controller
{
[Route("")]
public ActionResult Index(string projectName)
{
...
}
}
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