You can test your "normal" Spring MVC Controllers using the MockMvc class like so:
mockMvc
.perform(get("/my/fine/path"))
.andExpect(status().isOk());
From the Spring Reference on Handler Mappings:
Since there is really no such thing as a URL within a Portlet, we must use other mechanisms to control mappings. The two most common are the portlet mode and a request parameter, but anything available to the portlet request can be used in a custom handler mapping.
Is MockMvc only for "normal" Controllers or is there a way of using it when testing Portlet Controllers?
Checkout spring-test-portlet-mvc (https://github.com/markusf/spring-test-portlet-mvc), which exposes the features of MockMvc to the Portal context!
Related
I am converting an Asp.Net Web Api project to Asp.Net Core with .net6.
This project uses a custom Api-Key authentication and authorization method to give access to some of the controllers and actions.
In the old project, when opening the swagger documentation, the only controllers and actions displayed are the ones that do not require authentication.
Once the user inserts the api key and clicks on Explore button, the authorized controllers and actions shows up in documentation.
To do this, in the legacy project, I used IOperationFilter and IDocumentFilter to hide controllers and actions if not authorized.
This is working because when you click on Explore button after providing the api key, the page is refreshed and, at every refresh of the page, the IOperationFilter and IDocumentFilter are applied.
In Asp.Net Core, it seems that the IOperationFilter and IDocumentFilter are applied only at startup, and, in addition, the new Authorize button does not reload the page, and works only client side to provide authorization to the subsequent user interactions with the Try it out button present on every action.
Is it possibile to do something similar in Asp.Net Core, or should I drop that feature in the new version?
I found something may help you :
In asp.net core Swagger construct the UI page with a json file as below :
app.UseSwaggerUI(c=>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json","SwaggerFilterv1");
});
This json file is constructed with the options you configured when you registed the service
Then I tried to copy the content of json file to the static file in the project ,deleted part of the path(you could also apply the filters and copy the json file directly ),and replaced the json file constructed by .net core
It worked as excepted : Some of the Api was missing
and you may inject your js file to control it(Add a request header you if auth succeeded and refresh the page and check request header with middleware):
app.UseSwaggerUI(c=>
{
......
c.InjectJavascript("")
});
I tried to branch the pipeline(I omitted the Authentication process just tried to check the query para):
app.UseWhen(x =>x.Request.Query.ContainsKey("Key"),
app =>app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/somejson.json", "SwaggerFilter v1");
}));
app.UseWhen(......)
The Result:
I'm attempting to wire up Hangfire in my ASP.NET application (not Core) using the Global.asax.cs route explained in their documentation. However, none of their extensions methods on GlobalConfiguration.Configuration seem to be working for me. It appears, for one example, that SetDataCompatibiltyLevel() method extends Hangfire.IGlobalConfiguration, which my GlobalConfiguration.Configuration does not inherit from. I even backed off a few versions of Hangfire and it doesn't seem to make a difference. When I attempt to access the extensions method directly, I get this:
Prefix GlobalConfiguration class with the Hangfire namespace – System.Web.Http namespace defines its own GlobalConfiguration class, so you get a conflict. And that another class is referenced, most likely because you have the System.Web.Http namespace included in the beginning of the file.
Hangfire.GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibiltyLevel.Version_170);
You can also combine all the calls to the GlobalConfiguration class in a single chain:
Hangfire.GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibiltyLevel.Version_170)
.UseXXX()
.UseYYYStorage();
We've got a JAX-RS application that runs on Apache TomEE. We slightly customize the default Jettison provider to better adhere to JSON conventions used by JavaScript frontend. TomEE allows to do it via its resources.xml file:
<resources>
<Service id="jettison" class-name="org.apache.cxf.jaxrs.provider.json.JSONProvider">
serializeAsArray = true
dropRootElement = false
arrayKeys = members,roles
supportUnwrapped = true
writeXsiType = false
</Service>
</resources>
Now we are migrating to GlassFish v4.1, and we notice that JSON output differs from what we had in TomEE - thus completely breaking frontend. I'm looking for similar mechanism to customize JSON marshaller in GlassFish. In fact, I'm already a little bit stuck with Jersey, MOXy, Jackson, Jettison. How do we know which JSON provider is actually used? How do we select one? How do we customize the behavior?
The application is pure JAX-RS and does not use any JSON processor directly, instead relying on marshalling of JAXB-annotated classes. Introduction of any non-JavaEE dependencies is highly undesirable, since the application is intended to be portable across containers (TomEE, GlassFish, some day WildFly). Config-file method, similar to TomEE, is preferable; programmatic way is acceptable, too - but only if portability is maintained.
Glassfish uses MOXy as the default provider. Internally it has the libraries to handle Jackson, Jettison, and MOXy, but the default is MOXy. There are two ways to disable MOXy
Set the Jersey property jersey.config.server.disableMoxyJson to true.
Register a different XxxJsonFeature that disables MOXy. For instance the JacksonFeature that comes with jersey-media-json-jackson
Note that Glassfish comes with a Jackson provider, but it is Jackson 1.x. If you want to use 2.x, instead of the using the jersey-media-json-jackson dependency listed above, it would be better to use the underlying Jackson provider dependency, which is
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.6.0</version>
</dependency>
You can register the JacksonJsonProvider or the JacksonJaxbJsonProvider for JAXB annotation support.
To configure Jackson, the easiest way to implement a ContextResolver, as seen in this answer. The JacksonJsonProvider will lookup this ContextResolver to retrieve the ObjectMapper used for (de)serialization.
You will also need to remember to disable MOXy, as mentioned above.
Also one thing to note is that this solution is portable. With JAX-RS, the only portable application configuration is through an Application subclass
#ApplicationPath("/api")
public class MyApplication extends Application {}
That being said, the disabling of MOXy in the case of Glassfish, is nothing more than setting a property. In the Application class, you can override getProperties() which returns a Map<String, Object>. This is where you can set the property. And because it s nothing more than a String (no outside dependencies), it remains portable
#ApplicationPath("/api")
public class MyApplication extends Application {
#Override
public Map<String, Object> getProperties() {
Map<String, Object> props = new HashMap<>();
props.put("jersey.config.server.disableMoxyJson", true);
return props;
}
}
As far as the above Jackson dependency, it is also a portable solution. It it nothing (JAX-RS) implementation specific. It implements and uses standard JAX-RS APIs
I've got a simple MVC4 site which uses ASP.NET webAPI and also MVC pages.
I'd like to use Ninject DI for both controller types but I'm wondering how this can be done?
I've got Ninject DI working for WebAPI, but now not sure how to share the same Kernel elegantly.
Should I be using some sort of Kernel singleton which both Dependency Resolvers can refer to?
Anyone had any experience with this?
Cheers.
You should use the same IKernel instance for a single application-level composition root, may be WebApi or MVC controllers.
If you are using Ninject.MVC3 package:
When the kernel is initialized in NinjectWebCommon.cs inside your App_Start folder, you already have access to it. For MVC controllers, you don't need to do anything else for Ninject DI to work.
But for WebAPI controllers, you need to use a DependencyResolver to inject dependencies into your controllers. Using this implementation for this resolver, you then set it to be the resolver for all your WebAPI controllers like this:
Bind the NinjectDependencyResolver to self (optional), inside RegisterServices in NinjectWebCommon.cs:
kernel.Bind<NinjectDependencyResolver>().ToSelf();
Set the WepAPI configuration to use your Resolver, usually inside WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
//Other initialization code
config.DependencyResolver = (new Bootstrapper()).Kernel.Get<NinjectDependencyResolver>();
}
This will fit your scenario for all controllers sharing the same IKernel.
Hope that helps!
Yes, you are right. There should be one kernel/ container for an application, because this will eleminate possible mistakes in the future.In case of multiple kernels, you may register an interface in a kernel, and then try to resolve it using another kernel, and the program crashes.Only After spending time debugging, you find out what was wrong,etc.
In addition, using a single kernel, you wouldn't have to register a same implementation multiple times.
I have a .Net Mvc4 project, I've added a WebApi Controller and a basic action in for an ajax call.
When I call the method I get:
Inheritance security rules violated while overriding member:
'System.Web.Http.WebHost.Routing.HostedHttpRouteData.get_Route()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.
I haven't made any custom modifications or set up anything for web Api to work (was I supposed to?)
I noticed the DefaultApi route is in my routeConfig.
I'm also using Unity Mvc4 & Unity Web Api packages, (which I've disabled to test if it was causing the issue but doesn't seem to be).
My controller is TestController
action:
public bool ClearAwaitingNotifications()
{}
& ajax call is going to: api/test/clearawaitingnotifications
How can I fix this?
My exception occured when hitting controller because:
WebApiConfig.Register(GlobalConfiguration.Configuration);
was never called, although the route existed inside my Routeconfig.cs. I think this occurred because I installed my Mvc4 project using a template, which installs some WebApi stuff and it is all a bit old. I then added this line into Global.ascx and received the same security warning but for this line in Global.ascx.
https://stackoverflow.com/a/18713412/314963 then helped me resolve the issue, and now everything is working. In short, it is because of installing Mvc project with a template, or because one of the libraries in webapi 4 was outdated.