Can Ajax access non-controller methods? - c#

I’ve got a class that contains many helping functions, that make easy to do many things for my web app. I have attempted to use Ajax and access this class but it didn’t work.
Am I trying something impossible? Can Ajax only access controllers?

The short answer. Yes, you can make ajax calls into a class outside of controllers via custom routes in the RouteConfig class in the RegisterRoutes method. Setting certain routes (say to your helper functions) to be ignored by the handlers and letting traffic flow through.
The most correct answer for your situation. You shouldn't. Any ease of use of the helper functions would be quickly diminished with the work you would have to do because you are now responsible for handeling all http protocols coming in and going out of your helper classes for communications from client to server and back.
...and your coworkers (or anyone inheriting your code) will end up loathing you for breaking convention without a real need to do so.
Instead of reinventing the wheel just set up a Helper controller your project and make that responsible for fielding http requests back and forth and wrapping your helper functions. It can be a bare bones controller that doesn't return any actionresults and you dont have to build views, it can just be responsible for returning Json with nothing else built out. It won't break convention, you will be able to take advantge of years of knowledge and buildout for http handeling AND your fellow devs won't want to murder you in your sleep because you did something just because you could.

Related

Authorization/Authentication in asp.net web api

I need to create a couple of simple methods using asp.net web api. I am very new to this so even the simplest thing is proving difficult for me. I want to decorate my api controller with [authorize] and [authenticate] for the obvious reasons.
My question is centred on how I call these methods from my ajax calls (which is how I'm intending to call them). I'm reading that I need to pass the user id and password with each of my calls but how do I do this using ajax? Or do I even need to do this manually or asp.net somehow does it for me (if that even makes any sense)? Because when I'm doing action calls that need to be authenticated/authorized using forms in mvc, I certainly don't do it expressly and I imagine somehow somewhere in the code it just gets done.
As is clear, I'm very lost. Any help is appreciated.

Should filter share code with webapi controller?

I got a webapi Authorize filter which does some security checks on the queryString for "Get" calls.
For post methods, since I need to peek at the payload to retrieve the object (moreover, that would make my filter dependent upon my dtos, which I'm not a huge fan either...), and since I didn't find an easy way to open the post payload in the filter, I ended the subject by making the check in a controller method.
Obviously, the logic is the same in both cases.
So I put the validation logic in an abstract controller and make it "public static" so they can be called from the filter and from all inheriting controllers. I've read the google results from the follwoing query (avoiding calling static methods), and truth be told, I also find this ugly and untestable.
But what would be an elegant alternative ?
I've considered creating a (static ?) helper class but I only find it's syntactic sugar around the same concept.
I also think that helpers should not be IOc'ed maybe I'm wrong here ?
Thanks for your input !
You should include the details of validations that you wanna do on the query string to help us understand the problem in more details. However based on the information provided I have following to say.
Creating a static method in Controllers and accessing it in Filters is more ugly than exposing DTOs to Authorize Filter. The controllers acts as service layer and Filters are (to some extent) part of it(service layer) too. So there is nothing wrong if you have to expose DTOs to Filters. It can simply be seen as "DTOs being exposed to service layer".
However, if you really wish to avoid it, put an abstraction as part of your service layers which can be exposed to the Filters. Like you can create a interface (and its implementations) that exposes a validation method for your purpose that can be consumed from within the Authorize Filter.

Build an API for Multiple

I'm building an API using WebAPI that will be accessed via AJAX calls. However, the API controller will need more than just one POST method. I understand I can specify {action} in my routing, but because I've seen that this is not recommended - am I using the right tool? So 2 questions:
Is Web API the best tool for this, or is there something else I should be using?
Why should I not use more than one POST method in a WebApiController? Is including {action} in my routing a good enough solution to this problem?
1. Is Web API the best tool for this, or is there something else I should be using?
I think WebAPI is a fine choice for you, regardless of whether you have one or many POST calls per controller.
2. Why should I not use more than one POST method in a WebApiController?
To remain RESTFul you'll want a controller per entity type. Without getting too deep into details, a POST against a specific type of entity should be the 'ADD entity' call, and why would you have more than one of those? Having said that, you don't have to be fully RESTFul... if your requirements suite a multi-POST model then go for it, you can always refactor later if necessary.
...Is including {action} in my routing a good enough solution to this problem?
Again, if your goal is to be RESTFul then this isn't a great practice. However, if you have needs that are best achieved using action routings then go for it. REST is not the only model.

How can I reduce the number of classes used for RPC calls?

I'm currently working on a project that uses a custom server protocol for an API which functions much like RPC. To fit the PRISM architecture though, the number of classes and amount of boilerplate to support these functions are ballooning rapidly. Please note I inherited this codebase, and I don't have enough time to go around rewriting too much right now.
Basically the problem is that when the repository is making a call to the service proxy, we have to pass through parameters via JSON to the server, which means we need a RequestParameters object to serialize. We then receive a response which doesn't always look the same, so most calls have unique ResponseParameters as well. Finally, there's also an event structure, where an event is returned from the server but is distinguished by a text field, meaning we then have to write an event router, route each event to its specific section, and then route it further from there, and create a unique event class for each event.
In this fashion, if I want to make a call that returns the result as an event, I need to make two methods, three classes, and add the event entry to the appropriate event router, and most of those classes are time consuming boilerplate.
How can I change the structure of this to address the class bloat and improve the routing concept?
Some techniques that help with this short of a major overhaul:
Abstract the boilerplate into base classes that use generics
Code generation (via T4 built into VS or a 3rd party tool like
PostSharp)
Within certain scopes, define things as "dynamic"
rather than creating classes for them (your event code/router seem
like a good candidate for this)

REST based MVC site and/or WCF

I know there are actually a number of questions similar to this one, but I could not find one that exactly answers my question.
I am building a web application that will
obviously display data to the users :)
have a public API for authenticated users to use
later be ported to mobile devices
So, I am stuck on the design. I am going to use asp.net MVC for the website, however I am not sure how to structure my architecture after that.
Should I:
make the website RESTful and act as the API
in my initial review, the GET returns the full view rather than just the data, which to me seems like it kills the idea of the public API
also, should I really be performing business logic in my controller? To be able to scale, wouldn't it be better to have a separate business logic layer that is on another server, or would I just consider pushing my MVC site to another server and it will solve the same problem? I am trying to create a SOLID design, so it also seems better to abstract this to a separate service (which I could just call another class, but then I get back to the problem of scalability...)
make the website not be RESTful and create a RESTful WCF service that the website will use
make both the website and a WCF service that are restful, however this seems redundant
I am fairly new to REST, so the problem could possibly be a misunderstanding on my part. Hopefully, I am explaining this well, but if not, please let me know if you need anything clarified.
I would make a separate business logic layer and a (restful) WCF layer on top of that. This decouples your BLL from your client. You could even have different clients use the same API (not saying you should, or will, but it gives you the flexibility). Ideally your service layer should not return your domain entities, but Data Transfer Objects (which you could map with Automapper), though it depends on the scope and specs of your project.
Putting it on another server makes it a different tier, tier <> layer.
Plain and simple.... it would be easiest from a complexity standpoint to separate the website and your API. It's a bit cleaner IMO too.
However, here are some tips that you can do to make the process of handling both together a bit easier if you decide on going that route. (I'm currently doing this with a personal project I'm working on)
Keep your controller logic pretty bare. Judging on the fact that you want to make it SOLID you're probably already doing this.
Separate the model that is returned to the view from the actual model. I like to create models specific to views and have a way of transforming the model into this view specific model.
Make sure you version everything. You will probably want to allow and support old API requests coming in for quite some time.... especially on the phone.
Actually use REST to it's fullest and not just another name for HTTP. Most implementations miss the fact that in any type of response the state should be transferred with it (missing the ST). Allow self-discovery of actions both on the page and in the API responses. For instance, if you allow paging in a resource always specify in the api or the webpage. There's an entire wikipedia page on this. This immensely aids with the decoupling allowing you to sometimes automagically update clients with the latest version.
Now you're controller action will probably looking something like this pseudo-code
MyAction(param) {
// Do something with param
model = foo.baz(param)
// return result
if(isAPIRequest) {
return WhateverResult(model)
}
return View(model.AsViewSpecificModel())
}
One thing I've been toying with myself is making my own type of ActionResult that handles the return logic, so that it is not duplicated throughout the project.
I would use the REST service for your website, as it won't add any significant overhead (assuming they're on the same server) and will greatly simplify your codebase. Instead of having 2 APIs: one private (as a DLL reference) and one public, you can "eat your own dogfood". The only caution you'll need to exercise is making sure you don't bend the public API to suit your own needs, but instead having a separate private API if needed.
You can use RestSharp or EasyHttp for the REST calls inside the MVC site.
ServiceStack will probably make the API task easier, you can use your existing domain objects, and simply write a set of services that get/update/delete/create the objects without needing to write 2 actions for everything in MVC.

Categories

Resources