I'm developing web API solution for authorization, we decorated each controller action method with the BasicHttpAuthorizeAttribute class with inherits from AuthorizeAttribute.
public class BasicHttpAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
For every request, I see OnAuthorization method is called twice. when I check the callstack, all the request is made by same thread/processId. I'm using UnityContainer. I registered by Custom Authorize in WebApiConfig.cs Please let me know the reason for calling twice.
If you register a filter in webapiconfig.cs it will run for every incoming request.
If you decorate an action with a filter, it will run for that action.
Since you registered the filter and decorated the action, it will run two times.
Related
This method when called in a WebAPI controller from the client via an AJAX call returns a 200 code but the user gets re-authenticated upon a page refresh. What am I doing wrong?
[HttpPost]
[Route("logout")]
public IHttpActionResult Logout() {
AuthenticationManager.SignOut();
}
This works in a standard MVC controller as an ActionResult and a full page view, but it does not work via AJAX.
It looks like you're using a custom AuthenticationManager class because the one built into the framework doesn't look like it has a SignOut method.
http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager(v=vs.110).aspx
If that is the case, then does your AuthenticationManager class use the Session to store user info? Because WebAPI controllers do not have the same type of access to session that MVC controllers do. Reference for session in WebAPI:
Accessing Session Using ASP.NET Web API
I need inputs related to Spring MVC, I have a URL to which a client will send a post request with an xml as the pay load. I plan to have a controller method which maps to the requested url, I want that xml to be validated/converted to an object using jaxb before controller method is executed. And also, the controller method should have only the object as the parameter to its methods and no httprequest etc.
So, how do I achieve this? Will interceptor be helpful? If yes, how will it be done?
I plan to use Spring 3.
Simply use #RequestBody in conjunction with #Valid on a method argument and that is all you need.
public void myRequestHandlingMethod(#Valid #RequestBody YourJaxbObject jaxbObject) { … }
I strongly suggest you take a look at the Spring reference guide
I have a DefaultModelBinder which I have inherited from and I have tried overriding the BindModel call and OnPropertyValidating call.
However when using ASP.NET MVC's built in Remote validation, when the controller action gets called it bypasses my DefaultModelBinder and so it doesn't bind/validate how I want it to.
I have registered it in my global.asax, any ideas?
Can anyone please let me know the difference between rest web service method call and normal method call.
I developed a website, in which I invoked a method in controller using the following way,
#RequestMapping("/something.do")
and now I changed the same method to web service. Now I invoke the same method like
#RequestMapping(method=RequestMethod.GET, value="/something.do",headers="Accept=application/json")
And the URL i used in the AJAX call before and after converting to web service is "something.do". Everything is working fine.
My question is, if it is Rest web service then my URL should be something like
locahost/ProjectDisplayName/something.do. But it is working fine even when I make ajax call with something.do in URL. If this is correct what is difference between them?
Or please correct me where I am wrong.
See when you make rest call, and intercept it using controller.
Then you can send different parameters along with the call.
You can format your url before call restTemplate.executeService(Object ... obj)
so that it will map to below method.
eg.
<code>
#RequestMapping(value = "/something/{id}", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody
testJsonMessage getDataById(
#PathVariable("id") String id) {
}
</code>
I'm trying to setup an 'Authorization' Filter on an Action, creating my own ActionFilterAttribute where I do a database lookup to determine if a user has access to a certain resource.
On my class inheriting from ActionFilterAttribute, I have created an Injected(Ninject) property to hold the service that I am using for the database access. I have a parameterless constructor so that I can use this as an attribute on my actions. In the 'OnActionExecuting' Method, I am able to gain access to the Injected property (it's not null), but the base DBCotext that it is using is closed.
This working fine, up until the RTM of MVC3, where the Release Notes stated:
Breaking Changes:
In previous versions of ASP.NET MVC, action filters are create per
request except in a few cases. This
behavior was never a guaranteed
behavior but merely an implementation
detail and the contract for filters
was to consider them stateless. In
ASP.NET MVC 3, filters are cached more
aggressively. Therefore, any custom
action filters which improperly store
instance state might be broken.
The first time I use this filter, it works as expected, but if I refresh the page or another user access this filter, I get the error:
The operation cannot be completed
because the DbContext has been
disposed.
which is what I guess I should expect given the breaking changes notes.
My question is this, what would be the preferred/recommended way of accomplishing what I need to do? Should this be in an ActionFilterAttribute, or should this 'authorization' be done somewhere else?
I'd do authentication in Application_AuthenticateRequest and authorization in your attribute using Thread.CurrentPrincipal, but your method should work too. You just need to count with fact that DbContext will be different for each request but your attribute won't. Something like this should do the trick (I'm assuming you are using DependencyResolver):
public class MyMightyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = (DbContext)DependencyResolver.Current.GetService(typeof(DbContext))
// authenticate, authorize, whatever
base.OnActionExecuting(filterContext);
}
}
I have been battling with this for a while and finally solved my problem. So here is my solution in the hope it may help someone else.
The setup:
1. I have an MVC3 project, a custom action filter that accesses the db using EF5 via a business service.
2. I use Unity and unity.MVC to resolve my dependencies on a per request basis.
3. I use property injection into my custom Action filter, as it has a parameterless constructor.
The result.
Dependency injection works correctly for all the services used by actions, my EF DbContext is correctly disposed of at the end of each request.
The Problem
Although my property dependency is resolved in my custom action filter, it contains a stale instance of my DbContext (e.g. it seems to have been cached from the previous request)
As mentioned in previous posts, MVC3 is more aggressive with filter caching and the state of a filter cannot be relied on. So the suggestion was to resolve the dependency in the OnActionExecuting method. So I removed my injected property and did just that called resolve on my unity container. However I still got a stale version of the DbContext. Any changes in the DB were correctly queried in my main actions, but the custom action filter didn’t pick them up.
The solution.
Unity.MVC Manages per-request lifetime by using child containers and disposing these at the end of each request. By resolving my dependency’s in the action filter from my unity container I was resolving from the parent container which is not disposed of on each request.
So rather than
IoC.Instance.CurrentContainer.Resolve<IService>();
I used this to obtain an instance of the child container rather than parent.
var childContainer = HttpContext.Current.Items["perRequestContainer"] as IUnityContainer;
var service = childContainer.Resolve<IServcie>();
I'm sure there must be a clean way to achive the same result, so please add suggestions.
Ok slight refinement to allow my unit test to inject a mock of the service.
1. remove the dependency resolve from the the OnActionexecuting and add two constructors.
public MyCustomActionfilter() : this(((IUnityContainer)HttpContext.Current.Items["perRequestContainer"].Resolve<IService>())
and
public MyCustomActionfilter(IService service)
{
this.service = service;
}
Now the constructor resolves your service and stores it as a private readonly. This can now be consumed in your OnActionExecutng function. Unit tests can now call the second constructor and inject a mock.