February 22, 2021 06:20 by
Peter
Sometimes we come across a scenario where we need to encrypt a sensitive key in appSettings section in Web.config file. This blog demonstrates the steps to encrypt a key and read the respective key in an ASP.NET application.
I have an appsettings key that is being called from .NET application. Before we are encrypting appsettings key in web.config.
Step 1 - Adding a section in configSections in web.config
<configSections>
<section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections
Step 2 - Add secureAppSettings section under configuration
<secureAppSettings>
<add key="Password" value="XXXXXXXX"/>
</secureAppSettings>
How To Encrypt a AppSettings Key In Web.config
Step 3 - Execute command from command prompt to encrypt secureAppSettings section
Open command prompt and execute the below commands.
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
aspnet_regiis.exe -pef "secureAppSettings" "your application web config path" -prov "DataProtectionConfigurationProvider"
After execution of the above command, secure app settings section encrypted as below.
Step 4 - Accessing appsettings key from .NET code
To access the encrypted key value in code, we can write it like below.
using System.Collections.Specialized;
var passwordValue = "";
var section = System.Web.Configuration.WebConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
if (section != null && section["Password"] != null)
{
passwordValue = section["Password"];
}
Excellent! We successfully encrypted to a key in appsettings in web.config. Similarly, we can do the same steps while deploying a Web application to IIS.
HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.
February 16, 2021 06:49 by
Peter
Working with JSON within Web Services recently has become the latest and greatest simply because it plays so nicely with others and can often be very easily serialized and deserialized to fit your needs.
There is just something rewarding about having a massive collection of complex objects that can be thrown into a simple string and passed across however you see fit and then completely regenerated in its original collection in just a handful of code.
However sometimes these strings can get big and I mean really big, like exceeding default values big, and when this happens, exceptions happen. This post will cover a few ways that you can prevent a nasty InvalidOperationException that may look something like this with ease:
The Problem
You decide that paging data is for losers and decide to pull a graph of all of the data within your database, which will hypothetically contain thousands of complex objects, each with additional properties of their own. If your dataset is large enough, you’ll find yourself quickly exceeding the bounds that your Serializer can handle and you’ll be met with an exception and no data.
The Solution
There are three basic methods of handling this depending on your current environment:
Setting the MaxJsonLength property default value within your web.config. (This will only apply to web-services that handle JSON).
Setting the MaxJsonLength property of a JavascriptSerializer object to perform your serialization.
If you are using MVC4 to handle returning your JSON values, you may want to override the default JsonResult() ActionResult and change the maximum size manually.
Either of these changes will help you avoid any bumps in the road when passing across your large JSON values.
Option I: The MaxJsonLength Property for handling JSON in Web Services
The MaxJsonLength property which can be set within the web.config of your application controls the maximum size of the JSON strings that are accepted by the JsonSerializerclass. The default value is 102400 characters.
In order to increase the size of this value – you can just add the following code to your web.config file and set it to the value that you desire:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<!-- Update this value to change the value to
a larger value that can accommodate your JSON
strings -->
<jsonSerialization maxJsonLength="86753090" />
</webServices>
</scripting>
</system.web.extensions>
</configuration>
It is important to know that this setting within the web.config will only apply to actual Web Services that handle your JSON strings using the internal JsonSerializer. If you are still encountering issues after applying this change, you will likely want to continue reading and consider using an instance of the JsonSerializer class to handle setting this value.
Option II: Using the JavaScriptSerialzier and the MaxJsonLength Property to Handle Serializing JSON Values
Using an instance of a JavascriptSerializer will not actually inherit the previously defined within the web.config (as the web.config only applies to Web Services that handle the JSON) so you can easily just create an instance of the serializer and set the property accordingly:
// Creates an instance of your JavaScriptSerializer
// and Setting the MaxJsonLength
var serializer = new JavaScriptSerializer() { MaxJsonLength = 86753090 };
// Perform your serialization
serializer.Serialize("Your JSON Contents");
This will allow you to easily your larger data and adjust your maximum size easily.
Option III: Overriding the MVC4 JsonResult Action Result to Handle the Maximum Size
Much like the previous examples, every time that you are going to return a JsonResultyou can simply add the MaxJsonLength property to a specific value depending on the context of your specific action:
return new JsonResult() {
Data = "Your Data",
MaxJsonLength = 86753090
};
Or using the Json() method:
JsonResult result = Json("Your Data");
result.MaxJsonLength = 8675309;
However, if you want a more widespread solution that you could use within a single area of your application, you may want to consider overriding the JsonResult class and set your value within this newer class:
// This ActionResult will override the existing JsonResult
// and will automatically set the maximum JSON length
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue // Use this value to set your maximum size for all of your Requests
};
}
From a JSON to a JMAN
Those are just a few methods that you should be able to use if you ever encounter an issue when passing larger JSON strings across your Controllers or through the use of Web Services. I am sure that there are likely several other ways to handle these same problems, but hopefully one of these will help you out if you are in a tight spot.
HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.
February 3, 2021 08:48 by
Peter
Recently, one of my team members faced this error while implementing Swagger in ASP.NET core.
Environment Details
- Visual Studio 2019
- ASP.NET Core 3.1
- Swashbuckle.AspNetCore 5.6.3
Error
Unable to resolve service for type ‘Swashbuckle.AspNetCore.Swagger.ISwaggerProvider’ while attempting to Invoke middleware ‘Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware
The issue was with the Swagger generator. The swagger generator was not called or registered in container services of the startup file.
Below code: (startup.cs file) add services.AddSwaggerGen(),
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//...other methods added to servces
//...
//...
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen();
//....other methods added to servces
//...
}
Additionally, you can modify the information displayed in swagger UI with the following code:
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "My Peter API",
Description = "Peter ASP.NET Core Web API",
TermsOfService = new Uri("https://Peter.com/terms"),
Contact = new OpenApiContact
{
Name = "Rijwan Ansari",
Email = string.Empty,
Url = new Uri("https://Peter.com/spboyer"),
},
License = new OpenApiLicense
{
Name = "Use under Open Source",
Url = new Uri("https://Peter.com/license"),
}
});
});
This modification resolved the issue/error.
HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.