Solve json capitalization - asp.net

When I access an ASP.NET web api using angular from the same web site, all the first letter lowercase, even if they aren't lowercase on the server.
However, if I move the API's to a different web site and enable CORS, I will receive the JSON exactly as the properties are written on the server.
Is there some way to control this difference? It becomes a mess when I need to move an API to a different web site

The default for serializing output to JSON has changed so you may encounter this issue when migrating .Net frameworks. You can read more about the issue here or here but to resolve you can specify the DefaultContractResolver.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}

In your Owin Startup add this line...
public class Startup
{
public void Configuration(IAppBuilder app)
{
var webApiConfiguration = ConfigureWebApi();
app.UseWebApi(webApiConfiguration);
}
private HttpConfiguration ConfigureWebApi()
{
var config = new HttpConfiguration();
// ADD THIS LINE HERE AND DONE
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.MapHttpAttributeRoutes();
return config;
}
}

JSON is case sensitive as a rule JSON keys should have matching case. Some unix servers will ignore case sensitivity but I believe windows servers enforce it.
The error is in the naming conventions in the api or code requesting/processing those keys. Best to use lowercase keys using a under_score as the seperator instead of camelCasing.
http://jsonrpc.org/historical/json-rpc-1-1-alt.html#service-procedure-and-parameter-names
ref: When is case sensitivity important in JSON requests to ASP.NET web services (ASMX)?

Related

Call SignalR Hub From Another .Net Project

I've got SignalR hubs in one .NetCore project and SignalR clients in another .NetCore project (to comply with internal infrastructure guidelines). I'm struggling with how to implement the client code that will provide the connection to the hubs. All my projects build fine, I'm just missing the connectivity part.
Client Project:
public class MyClientController
{
private readonly IHubContext<MyHub, IMyHubClient> _hub;
public MyClientController(IHubContext<MyHub, IMyHubClient> hub)
{
_hub = hub;
// THIS NEVER GETS CALLED/HIT BECAUSE I DON'T KNOW HOW TO REGISTER IT
_hub.Clients.All.BroadcastMessage("Notify", $"Hello everyone. This has been constructed");
}
}
I'm guessing I need to do some configuration in the Startup.Configure() method? I've installed the client package already,
EDIT: I added the following code, but it's complaining about the format (remember, this is not a relative path, it's in another service).
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHub>("http://localhost:60913/myHub");
}
Am I on the right path here?
The connection is made by mapping a route to your hub class. The docs have a good example. This includes:
// Add to services collection
services.AddSignalR();
// Map the route "/chathub" to a ChatHub class
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
});
By the way, a hub can be a standalone class not associated to a controller.

Define different APIs to accept different size limits in ASP.Net Core 2.2

I have a controller which contains different methods. How can I define specific request size limit for each method?
I've tried these links, but I don't want to define a global size in web.config or startup
Asp.net Core 2.0 RequestSizeLimit attribute not working
Asp.net Core RequestSizeLimit still executes action
HTTP Error 404.13 - asp.net core 2.0
Increase upload file size in Asp.Net core
[HttpPost]
[RequestSizeLimit(1000000)]
public void MyMethod1([FromBody] string value)
{
// Do something
}
[HttpPost]
[RequestSizeLimit(2000000)]
public void MyMethod2([FromBody] string value)
{
// Do something else
}
I expect MyMethod1 accepts only requests with size less than 1000000 bytes and MyMethod2 accepts requests with size less than 2000000 bytes. But this does not work and they accept requests with any size.
What is the issue here?
That solution you tested its used for MVC not .Net Core
What I Found mostly people using solution (Global Solution) in the below:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>{
options.Limits.MaxRequestBodySize = 52428800; //50MB
});
}
but it have different ways for it like MiddleWare like below:
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"),
appBuilder =>{
context.Features.Get<IHttpMaxRequestBodySizeFeature>
().MaxRequestBodySize = null;
//TODO: take next steps
});
Sorry For My Bad English :)
Source => Helper Link

Building JVM for Scala 2_11

This is a question about the project https://github.com/DiUS/pact-jvm.
Problem
When I am validating pacts I need to be able to use client side authentication, as the providers actually require client side authentication. I'll prefix what I am saying with a declaration that I am not very familiar with groovy: I mostly program in scala, java or javascript. Having looked at the code I think that client side authentication is not currently supported, so I'd like to make a pull request with that support in it.
What I've done so far
I have managed to get Https working with a truststore: I copied the HttpTarget and created a HttpsTarget, and in the HttpsTarget specified the truststore in the providerinfo. Unfortunately looking at the code there doesn't seem to be a way of specifying the client certificate, so I need to change the providerinfo class to be able to specify where it is (in the same way the the truststore is provided).
My problem is that I've got the code compiling using the advice in the 'for contributors', but when I publish locally, I am only publishing for scala version 2_12. Because of version issues and binary incompatibilities between scala versions, I need to publish to scala 2_11. My skills with gradle are even less than my skills with groovy. I've done a search for all the references to scalaVersion, and found that there is quite a lot of logic around it, but I've not managed to track down where it is specified.
Question
If I can use client side authentication with the current pact validator could you let me know. If not, could you tell me how to publish the project with support for scala 2_11?
Thanks
In the end I made my own Http Target. My need is to run from Junit, not the general case, and this is good enough:
public class HttpsTarget extends HttpTarget {
public HttpsTarget(final int port) {
super("https", "localhost", port, "/", false);
}
static class HttpsClientFactory implements IHttpClientFactory {
#NotNull
#Override
public CloseableHttpClient newClient(Object o) {
SSLContext sslContext = // put here code to make ssl context
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLContext(sslContext)
.build();
return httpClient;
}
}
#Override
public void testInteraction(final String consumerName, final Interaction interaction, PactSource source) {
ProviderInfo provider = getProviderInfo(source);
ConsumerInfo consumer = new ConsumerInfo(consumerName);
ProviderVerifier verifier = setupVerifier(interaction, provider, consumer);
Map<String, Object> failures = new HashMap<>();
ProviderClient client = new ProviderClient(provider, new HttpsClientFactory());
verifier.verifyResponseFromProvider(provider, interaction, interaction.getDescription(), failures, client);
reportTestResult(failures.isEmpty(), verifier);
try {
if (!failures.isEmpty()) {
verifier.displayFailures(failures);
throw getAssertionError(failures);
}
} finally {
verifier.finialiseReports();
}
}
}

Push data server to client web app, how to?

(Regarding Web apps, asp.net 5)
I'm new to this stuff, i want to push data from the server to the client. Displaying 'real-time' data on a website. (something like a chat window).
How should i realize this? I've read about SingalR, but most information seems to be outdated? Is this still a good choice?
For example, one of the problems i run into is when i try to add this:
app.MapSignalR();
to my startup.cs
Error CS1061 'IApplicationBuilder' does not contain a definition for 'MapSignalR' and no extension method 'MapSignalR' accepting a first argument of type 'IApplicationBuilder' could be found
Can someone point me in the right direction?
I believe you can do this with a bridge between IAppBuilder and IApplicationBuilder as shown here:
public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure)
{
app.UseOwin(addToPipeline =>
{
addToPipeline(next =>
{
var appBuilder = new AppBuilder();
appBuilder.Properties["builder.DefaultApp"] = next;
configure(appBuilder);
return appBuilder.Build<AppFunc>();
});
});
return app;
}
Which you would then call from startup to start SignalR:
public void Configure(IApplicationBuilder app)
{
app.UseAppBuilder(appBuilder =>
{
appBuilder.MapSignalR();
appBuilder.Run(context =>
{
});
});
}
Some context, excerpted from the link above:
[In ASP.NET 5, now ASP.NET Core 1.0] the Startup class conventions
have been refined. Katana [the previous version] would search for an
assembly that specified the OwinStartup attribute and then fallback
to searching all assemblies for a class named Startup or
AssemblyName.Startup. ASP.NET does not define an attribute and it only
searches the primary application assembly for a type named Startup (in
any namespace). The Configuration(IAppBuilder app) method is now
Configure(IApplicationBuilder app)...
Middleware that can’t remove their IAppBuilder or OwinMiddleware
dependencies can use a modified approach to run in ASP.NET 5. See this
linked sample for an IApplicationBuilder extension that provides an
IAppBuilder for use with Katana v3 based middleware. This extension
creates a new AppBuilder instance and then wraps the OWIN pipeline
builder pattern around it to integrate into ASP.NET 5.

IdentityManager with VNext

Has anyone tried using IdentityManager with vNext?
I'm having problems with the app.UseIdentityManager(IdentityManagerOptions) extension method.
It doesn't exist.
So I tried using the extension method made for UseIdentityServer (found here) by changing all the server related aspects to manager.
When I do that, I get the System.NullReferenceException in line 43.
Any kind of advice on how to go about with the extension method will be really appreciated
I am using ASPNET 5 beta6 and I got this to work.
Try using this updated IApplicationBuilder extension found in the Samples repo on dev branch. Repurpose the method to accept IdentityManagerOptions rather than IdentityServerOptions and edit the builder to UseIdentityManager
In short here is what my extension method looks like
public static class IApplicationBuilderExtensions
{
public static void UseIdentityManager(this IApplicationBuilder app, IdentityManagerOptions options)
{
app.UseOwin(addToPipeline =>
{
addToPipeline(next =>
{
var builder = new AppBuilder();
var provider = app.ApplicationServices.GetService<IDataProtectionProvider>();
builder.Properties["security.DataProtectionProvider"] =
new DataProtectionProviderDelegate(purposes =>
{
var dataProtection = provider.CreateProtector(string.Join(",", purposes));
return new DataProtectionTuple(dataProtection.Protect, dataProtection.Unprotect);
});
builder.UseIdentityManager(options);
var appFunc =
builder.Build(typeof (Func<IDictionary<string, object>, Task>)) as
Func<IDictionary<string, object>, Task>;
return appFunc;
});
});
}
}
I'm using vNext and I've noticed that many things have changed and will continue to change.
For my own needs I've been able to get identity up and running fairly easily and there are two steps that I've had to take to get it running properly. What I've done should work for you as well.
In your StartUp.cs you will need to make sure you add the following to the ConfigureServices method:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
In addition to that you will need to configure your app to use identity and to do this you need to do the following in your Configure() method:
app.UseIdentity();

Resources