Can I use Db context inside an HttpModule? - c#

I have to implement HttpModule for a condition which should return http status 401 if condition get failed before request hits the controller. In this condition i need to access database to compare some values, My question is, Is it a good practice to use dbcontext inside the HttpModule implementation? or there are any other ways to achieve the same.
NOTE: I know the same can be done through the Custom Authorize attribute, but for that i need to change in lot of places.
Any help will be appreciated.

Usually we have a base controller in all our applications and that will be handling all the filtering and condition checking based on the request url, role and some more conditions, if all meets only the url redirection will perform and the request will hit the actual controller.
My suggestion is to have some kind of mechanism to keep base controller or some OOP approach in all your controllers, that will be much easier when you want to modify something which are common behavior

Related

Can Ajax access non-controller methods?

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.

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.

Is it possible to set an instance variable or pass data to a controller from a custom authorize attribute?

I have an authorize attribute that extends System.Web.Http.AuthorizeAttribute and overrides the onAuthorization method. It queries the DB with a token that comes from the request to see if the session is valid. From that, it knows the associated userId. I would like to somehow make the userId available to the controller of the action being called. Somehow setting an instance variable would be ideal because I want to unit test the controller. Perhaps that is not possible or there is a better way to go about doing it. Please let me know. I am using ApiController.
Thanks
Not sure if this is the appropriate way to handle this situation, but to answer my question, one can use actionContext.ControllerContext.Controller. From there I can call a setter or set a public instance variable Please let me know if this a bad approach. Regarding sessions with REST, I am not too concerned with having a pure REST implementation.

MVC4 Intercept ALL Requests that require Authentication

I'm wanting to require that all users have some additional information filled out before they proceed to ANY section of the site that requires authentication.
If possibly I'm wanting to catch on [Authorize] annotations, but ignore any #User.IsInRole("something")
Is there a method that I can override in Global.asax or ?
I'm only hoping to grab the annotations because my only use for .IsInRole() is to display different info to them and I want the links there so they actually see what is needed to get to the annotations. Hope this makes sense (kinda tired).
You can override the AuthorizeAttribute itself; that'll give you access to the OnActionExecuting() method that gets fired when an action marked with [Authorize] gets called. From there you can either add your own auth logic or call through to the base methods, and then redirect to the appropriate error or form if the extra data needs filling in. You should be able to tack on their original request as a return URL query parameter so that the user can continue to wherever they were going once the extra data is taken care of. You'll then need to replace all uses of [Authorize] with this custom attribute, but find and replace should take care of that.

What to use instead of OnActionExecuting? ASP.NET MVC

I've got some things I do in the OnActionExecuting method in a BaseController, that all my other controllers are based off of.
I'm doing some simple things like putting a variable into ViewData that "nearly" all of my views will need, and populating a couple properties that my controllers use.
Thing that bugs me is, this work is being done even on actions that don't need it. Is there a better place to hook into to more efficiently perform this work? In case I ever need to something a little "heavier" than what I do now (i.e. DB access, etc...).
UPDATE: I'm more specifically referring to a typical controller scenario. Where there are several actions that simply show a view. And a few that take a form submission, do some work, and redirect to another action.
In this case, I want the actions that show views to use the work that is done in the OnActionExecuting method. But the actions that accept form submissions, the work being done in OnActionExecuting is not being used and therefor just adds unnecessary processing time.
Maybe I'm not explaining it very well... hope it's clearer now.
TIA!
If it's easier to blacklist actions (by attributing actions for which this logic shouldn't be performed) than whitelisting actions, you could create a [SuppressWhateverLogic] attribute and apply it to the methods you want to be blacklisted. Then modify your OnActionExecuting() method to look for this attribute (via ActionExecutingContext.ActionDescriptor.IsDefined()), and if the attribute exists then bail out of the logic.
If it's easier to whitelist actions, move the logic out of Controller.OnActionExecuting() and create a custom [MyLogic] filter by subclassing ActionFilterAttribute. Add the logic to MyLogicAttribute.OnActionExecuting(), then attribute the methods you want with [MyLogic] to associate the logic with those methods.
Create a second "AdvancedBaseController" which derives from BaseController?

Categories

Resources