ActionMethodSelectorAttribute equivalent in ASP.NET Web API? - asp.net-web-api

Is there a Web API equivalent to the MVC ActionMethodSelectorAttribute?
My specific purpose is this: I have, for example, a ResourceController and when I POST to the controller, I'd like to be able to receive a single resource (Resource) or a list (IEnumerable<Resource>).
I was hoping creating two methods with different parameters would cause the deserialization process to do some evaluation but this doesn't seem to be the case (and frankly, I don't think it's efficiently realistic with the combination of content negotiation and the fact that many data formats, like JSON, make it difficult to infer the data type). So I originally had:
public HttpResponseMessage Post(Resource resource) {...}
public HttpResponseMessage Post(IEnumerable<Resource> resources) {...}
...but this gets the "multiple actions" error. So I investigated how to annotate my methods and came across ActionMethodSelectorAttribute but also discovered this is only for MVC routing and not Web API.
So... without requiring a different path for POSTing multiple resources vs. one (which isn't the end of the world), what would I do to differentiate?
My thoughts along the ActionMethodSelectorAttribute were to require a query parameter specifying multiple, which I suppose is no different than a different path. So, I think I just eliminated my current need to do this, but I would still like to know if there is an equivalent ActionMethodSelectorAttribute for Web API :)

I haven't seen a replacement for that method (there is an IActionMethodSelector interface but it is internal to the DLL). One option (although it seems like it might be overdoing it) is to overload the IHttpActionSelector implementation that is used.
But changing gears slightly, why not always expect an IEnumerable<Resource>? My first guess is that the collection method (that takes IEnumerable<Resource>) would simply loop and call the single value (just Resource) function?

Related

Implementing Front Controller pattern

I've been trying to implement a Front Controller on a VBScript (ASP Classic) based system for a couple of days. I come from a ASP.NET MVC and Java background, where MVC implementations are kind common and mostly done by existing frameworks. On VBScript, however, there's almost nothing done in this area, so it is the reason why I'm trying to do it by myself. I used this and this article as a guide on how to implement it.
I believed at first that I'd need to define some constant parameters for each request, so I created 3:
class_command 'which command responsible to execute the correct class handler
action 'which method of the class handler to execute
action_params 'which parameters the action will need
Next, I defined a generic controller handler for treating the request:
Public Function Controller_Handler(action_params)
Its task is to extract the constant parameters (class_command, action, action_params) and treat any errors (I'll add later a filter to process it) that might come like absence of the constant parameters or authentication problems.
But soon I realized a problem: how will the handler know which command to call, since the request is a string? I can't simply converting it to class using reflection, because VBScript (I think) doesn't have a reflection library or built-in feature.
So I thought I could create a Switch Case like this:
Select action_Params.Item("action_params")
Case "command_A"
' Call Command A
Case "command_B"
' Call Command_B
.
.
.
Case "Command_X"
' And so on
End Select
But that would kinda procedural way to do it. Next I thought of creating a XML file which would map all the commands and other stuff.
So my question is: is this a good way of implementing a Front Controlller pattern, considering VBScript limitations? If not, could you provide a guidance (hopefully with some example, even a simple one) on how can I do it?
Moving from classic to .net/mvc I can share what I did in classic asp to try to emulate this behavior as closely as possible without making it too much of a maintenance issue.
Using URL Rewrite in IIS are my routes. I usually just make one route and direct/rewrite all inbound requests to one controller.asp page to simplify things and not have a bunch of rules and controller redirects directly in my URL Rewrite settings for maintaining it easier (for me).
Using Request.ServerVariables("HTTP_X-ORIGINAL-URL") in controllers.asp you can grab the actual URL that was entered, which return something like.. /real/url
In controllers.asp programatically call the view based on the entered url using Server.Execute("view1.asp")
I have one class file called routes.asp that is included in each model/class file, and helps me gather the URL properties oRoute.GetPath_FirstDirectory() and so on. The model/class file then uses this data to create its property values that can be consumed by the view. Using CLASS_INITIALIZE in each model/class to populate itself from the route/url, or it could also be done directly in the view.
In the respective view I include my class/model file (if even needed) using <!--#include file="class.asp"--> then simply open Set Model = new cModelClass to initialize and start using it in the view. I don't include the class in the controllers.asp because the view will not inherit any of the variables from controllers.asp when using Server.Execute() to the view. So I include it directly in the view.
Error handling can be at multiple levels here, but ideally its in the controllers.asp. Specific error handling is usually at the actual model/class CLASS_INITIALIZE to avoid redundant use of the class in the controller, since it's already going to be initialized in the view.
Now this is not exactly what goes in in .Net mvc, but it's the best way I've come up with, and easiest to maintain for me. Maybe others have other implementations, but this is mine and solely based on my experience. And so far, it's been working out pretty well.

Attribute Routing vs Convention

Playing around with the Web.API 2.0 stuff- in particular Attribute Routing. The docs state that you can have attribute routing AND the 1.0 routing by convention... but these two don't seem to play that well together. For example, given these two methods:
public override HttpResponseMessage PutModel(SampleForm form)
[HttpPut("approvesampleform/{form}")]
public string ApproveSampleForm([FromBody]SampleForm form)
While I can call http://localhost/api/sampleform/approvesampleform just fine, a PUT to http://localhost/api/sampleform/ generates a Multiple actions were found that match the request error.
Is there any way that if a method is marked with the attribute routing it is ignored by the convention? This would be ideal... but I don't see any way to accomplish this in the docs.
Note: I don't see a asp.net-web-api-2 tag. Perhaps someone with more than 1500 rep can create it?
Right, RC (Release Candidate) did not have the logic where conventional routes cannot access attributed controller/actions. This change came post-RC. The scenario you are trying would work fine in post-RC bits.
Probably the docs you mentioned aren't very clear, but I think they mean that you could have attributed and convention based controllers work side-by-side and not particularly about mixing both attributed and conventional semantics in the same controller.
For time being you could probably use only attribute routing for your controller mentioned above.

Multiple Rails controller requests on one page

The other day I stumbled on Sandi Metz's rules, and one of them reads
When a call comes into your Rails controller, you can only instantiate one object to do whatever it is that needs to be done.
Still pretty new to Rails, but I always thought that my controller methods had some smell in them, and this confirmed it. I have a dashboard view for a parent model that displays information about their children (a different model) and the children's challenges(another model), all with different controllers. Here is an example of one of our controller methods.
def dash
#parent = current_user
#children = #parent.children
#completed_challenges = #parent.assigned_challenges.where("parent_id =?", #parent.id).where("completed =?", true)
#validated_challenges = #parent.assigned_challenges.where("parent_id =?", #parent.id).where("validated =?", true)
#enabled_rewards = #parent.enabled_rewards.where("parent_id =?", #parent.id)
end
I was wondering if I could send multiple requests to get all of these objects from their respective controllers as opposed to lumping them all in one request. I know I can do this with Ajax, but is there a way just doing multiple http requests when the page is loading?
I appreciate the help!
The answer is NO.
AJAX was built specifically for that purpose, to overcome the short-comings of multiple http requests. Plus multiple http requests while page load is frowned upon because of the performance slump. It might seem lucrative path for a small project, but when it scales, you will definitely run into huge holes.
Though I am not a big fan of it, but following the beaten path can save you a lot of effort in this case. :)
The recommended approach is using the Facade Pattern. A perfect example of how to handle this is provided by Thoughtbot in the "Only instantiate one object in the controller" section of this blog post:
http://robots.thoughtbot.com/sandi-metz-rules-for-developers
When a call comes into your Rails controller, you can only instantiate one object to do whatever it is that needs to be done.
I see the usefulness of this rule, but I think you can interepret it in a slightly different way. When you load a controller, you do want it doing as little as possible. This is a given.
In your case, though, you seem to have a lot of different bits of data to load. Besides looking ugly, you'll see that the code also tends to get bigger and bigger as your dashboard supports more and more metrics. You don't really want to be in a situation where the number of lines of code increases proportionally with the amount of data an application shows.
Instead, send one object - a dictionary of all the data that you need to show. And I'd suggest moving the construction of that dictionary off to a model (or better still, a service) that builds it up (possibly based on configuration of some sort). The controller should just be fetching that object from somewhere and sending it back in the correct format.

Code Design. How to access your api-key in your business logic?

It's a code design question :)
I have a DelegatingHandler which takes the http request header and validates the API-key. Pretty common task I guess. In my controller I call my business logic and pass along all business-relevant information. However now I'm challenged with the task to change behavior inside my business logic (separate assemblies) depending on certain api-keys.
Various possible solutions come to my mind...
Change business logic method signatures to ask for an api-key, too.
public void SomeUseCase(Entity1 e1, Entity2 e2, string apiKey);
Use HttpContext.Current to access the current request context. However I read somewhere that using HttpContext restrict my hosting options to IIS. Is there any better suited option for that?
var request = HttpContext.Current.Request; // next extract header information
Use Sessions (don't really want to go that road...)
What's your opinion on that topic?
I'd go for #1 although I don't like the idea of mixing in enivonmental stuff in business logic methods. But depending on your point of view you might argue the api-key is in fact logic-relevant.
Update #1:
I'm using a delegatingHandler to validate the apiKey and once it is validated I add it to the Request's Properties Collection.
The part in question is how the "api-key" or RegisteredIdentifier is passed along to the business logic layer. Right now I am passing the object (e.g. IRegisteredIdentifier) as a parameter to the business logic classes' constructors. I understand there is no more elegant way to solve this(?). I thought about changing the method signatures but I'm not sure whether it's interface pollution or not. Some methods need to work with the api-key, most don't. Experience tells me that the number will more likely grow than drop :) So keeping a reference to it in my bl classes seems to be a good choice.
Thank you for your answers - I think all of them are part of my solution. I'm new to StackOverflow.. but as far as I can see - I cannot rate answers yet. Rest assured I'm still thankful :)
I would suggest two different options.
Promote the value into a custom HTTP header (e.g. something like mycompany-api-key: XXXX ). This makes your delegating handler work more like a standard HTTP intermediary. This would be handy if you ever hand off your request to some secondary internal server.
Put the api-key into the request.Properties dictionary. The idea of the the Properties dictionary is to provide a place to put custom meta information about the request.
HTTP works hard to make sure authentication/authorization is a orthogonal concern to the actual request, which is why I would try and keep it out of the action signature.
I would go for option 1.
But you could introduce the entity RegisteredIdentifier (Enterprise Patterns and MDA by Jim Arlow and Ila Neustadt) in your business logic.
The api-key can be converted to a RegisteredIdentifier.
RegisteredIdentifier id = new RegisteredIdentitief(api-key);
public void SomeUseCase(Entity1 e1, Entity2 e2, RegisteredIdentifier id);
The business logic layer has a dependency on the API key. So I would suggest:
interface IApiKeyProvider
{
string ApiGet { get; }
}
..then have your BLL require that an object implementing that interface is supplied to it (in constructor, setup, or even each method that requires it).
Since in the future it might not be one API key. The key point is that this identifies the BLL is dependent on something, and defining a contract for the something.
Real-world example:
Then, in your DI container (Ninject etc), bind your own ConfigFileApiKeyProvider (or whatever) implementation to that interface, in the "place" (layer) that DOES have the API key. So the app that calls the BLL specifies/configures how the API key is specified.
Edit: I misunderstood the part about this being a "how-to-do-it-over-HTTP" question and not a code architecture/code design question. So:
HTTP header is the way to go in terms of transport

Should controller methods take arguments?

Given that there is file selection widget on the view and controller need to handle event of selecting file, should I rather write controller method:
public void fileSelected(String filePath){
//process filePath
}
or
public void fileSelected(){
String filePath = view.getSelectedFilePath();
//process filePath
}
The first approach seems to introduce less coupling between C and V: C don't know what exactly data does C need while handling given event.
But it requires creating a lot of verbose methods similar to getSelectedFile on V side.
On the other hand, second approach may lead to cluttered controller methods in more complex cases than in example (much more data to pass than just filePath).
From your own experience, which approach do you prefer?
The first approach is my favourite. The only difference is I would rather use an object (like Mario suggested) to pass arguments to the method. This way method's signature will not change when you add or remove some of the arguments. Less coupling is always good :)
One more thing:
If You want to try the second solution I recommend using a ViewFactory to remove view logic from the controller.
The first approach is the way to go;
public void fileSelected(String filePath){
//process filePath
}
The Controller should not care about how the View looks like or how it's implemented. It gets much clearer for the developer as well, when creating/updating the view, to know what an action in the controller wants. Also it makes it easier for method overloading.
Though, I don't know really how String filePath = view.getSelectedFilePath(); would work. Are we talking about parsing the View code/markup?
On the other hand, second approach may lead to cluttered controller methods in more complex cases than in example (much more data to pass than just filePath).
That's when you would create a View Model class (let's say we name it MyViewModel) to store all the properties that you need to send (may it be 10 properties) and then pass that in the action: fileSelected(MyViewModel model). That's how it's intended to be used and what the *ModelBinder's in asp.net mvc are there to help you with.
I think you need to look at this from a step back.
Worry less about how it gets in, and be more concerned with validation and error raising.
Tomorrow, your requirements could change and demand that you source the information via a different architectural approach. You could refactor the setup of [inputs / an input object] into a base controller class - or one of several classes for different controller domains.
If you focus on proper validation, whether within the controller (scrubbing) or outside of it (unit tests), then you perform more thorough decoupling though duck typing.
I would go with the first approach. It's reusable and separates concerns. Even if the method of getting the filePath in the future were to change, it won't affect your method's functionality.

Resources