简体   繁体   中英

Route Aliases in ASP.NET Web API 2

I have a Web API that allows users to access/manipulate resources that "belong" to other users. It contains many routes similar to this:

/users/{userId}/resource

I'd like a corresponding set of routes that do the same on behalf of the currently authenticated user:

/resource

Ideally I'd like to get the second set of routes working without doubling the number of actions in my controllers, but I'm struggling to find the right hook. Ideally, I'd like to add a MessageHandler (or something) that intercepts each request, checks if it matches a route, and if it doesn't, prepends "users/" + ID of the authenticated user to the route and checks again. What is the best way to accomplish this?

One constraint: I'm using attribute routing to implement the first set of routes and would ideally like to pull this off without sacraficing that.

The hook is the action selector, as you can see here: Routing and Action Selection in ASP.NET Web API .

You can implement your own action selector to achieve what you want. Here is a sample on how to do that: Magical Web API action selector . From the same page:

We will create a class that implements IActionSelector, as that would allow us to plug into the hook provided by the Web API under GlobalConfiguration.Configuration.Services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM