Do you know Visual Studio has this nice feature to send HTTP Requests using .http files. It's actually pretty neat.
We just have to create a file with .http extension.
![]() |
.http Files in Action |
Hope this helps!
Happy Coding.
Do you know Visual Studio has this nice feature to send HTTP Requests using .http files. It's actually pretty neat.
We just have to create a file with .http extension.
![]() |
.http Files in Action |
Hope this helps!
Happy Coding.
Azure Durable Functions now supports .NET 7.0 running in the Isolated worker process. It's still in it's preview stage, but it's super exciting.
In this post, let's see how we can get ourselves started in Azure Durable Functions in Azure Functions .NET Isolated Worker Process.
First, after creating a Function App that targets .NET 7 Isolated functions worker, we need to install the NuGet package: Microsoft.Azure.Functions.Worker.Extensions.DurableTask. Make sure you have checked Included prerelease checkbox if you are trying to install the package through Visual Studio NuGet Package Manager.
|
Microsoft.Azure.Functions.Worker.Extensions.DurableTask |
using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.DurableTask; using Microsoft.Extensions.Logging; namespace FunctionApp1; public class Function1 { [Function(nameof(TriggerHello))] public async Task<HttpResponseData> TriggerHello([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req, [DurableClient] DurableClientContext durableContext, FunctionContext executionContext) { ILogger logger = executionContext.GetLogger(nameof(Function1)); string instanceId = await durableContext.Client.ScheduleNewOrchestrationInstanceAsync(nameof(HelloPersonOrchestrator)); logger.LogInformation("Created new orchestration with instance ID = {instanceId}", instanceId); return durableContext.CreateCheckStatusResponse(req, instanceId); } [Function(nameof(HelloPersonOrchestrator))] public static async Task<string> HelloPersonOrchestrator([OrchestrationTrigger] TaskOrchestrationContext context, FunctionContext executionContext) { ILogger logger = executionContext.GetLogger(nameof(HelloPersonOrchestrator)); string result = await context.CallActivityAsync<string>(nameof(SayHello), "John Doe") + " "; result += await context.CallActivityAsync<string>(nameof(SayHello), "Jane Doe") + " "; result += await context.CallActivityAsync<string>(nameof(SayHello), "Joe Bloggs") + " "; result += await context.CallActivityAsync<string>(nameof(SayHello), "Fred Bloggs"); logger.LogInformation("HelloPersonOrchestrator says: {output}", result); return result; } [Function(nameof(SayHello))] public static string SayHello([ActivityTrigger] string name, FunctionContext executionContext) { ILogger logger = executionContext.GetLogger(nameof(SayHello)); logger.LogInformation("Saying hello to {name}", name); return $"Hello {name}!"; } }
|
Output |
Hope this helps.
Happy Coding.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); WebApplication app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseExceptionHandler("/error-development"); } else { app.UseExceptionHandler("/error"); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; using System.Net; namespace WebApplication1.Controllers; [ApiController] [ApiExplorerSettings(IgnoreApi = true)] public class ErrorController : ControllerBase { private readonly IHostEnvironment _hostEnvironment; public ErrorController(IHostEnvironment hostEnvironment) { _hostEnvironment = hostEnvironment; } [Route("/error-development")] public IActionResult HandleErrorDevelopment() { if (!_hostEnvironment.IsDevelopment()) { return NotFound(); } IExceptionHandlerFeature exceptionHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>()!; if (exceptionHandlerFeature == null) { return Problem( title: $"'{nameof(IExceptionHandlerFeature)}' not found."); } return exceptionHandlerFeature.Error switch { NotImplementedException notImplementedException => Problem( title: notImplementedException.Message, detail: notImplementedException.StackTrace,
statusCode: (int)HttpStatusCode.NotImplemented), _ => Problem( title: exceptionHandlerFeature.Error.Message, detail: exceptionHandlerFeature.Error.StackTrace) }; } [Route("/error")] public IActionResult HandleError() => Problem(); }
[HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { throw new NotImplementedException("Not implemented."); }
[HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { throw new Exception("Something happened."); }
![]() |
Development: StatusCode: 500 |
![]() |
Production: StatusCode: 500 |
In this post, let's see how we can disable implicit required model validation for non-nullable reference types when the nullable context is enabled in an ASP.NET Core Web Application.
Let's consider the following sample.
#nullable enable using Microsoft.AspNetCore.Mvc; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Register Services. builder.Services.AddControllers(); WebApplication app = builder.Build(); // Configure the HTTP request pipeline. app.UseHttpsRedirection(); app.MapControllers(); app.Run(); [ApiController] [Route("[controller]")] public class EmployeesController : ControllerBase { [HttpPost] public ActionResult<Employee> Create([FromBody] Employee employee) { return employee; } } public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public Employee(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } }
Here if we try to post a payload with null values for reference types that are not marked with nullable, ASP.NET Core by default is doing a model validation and throwing an error.
For example, here if we post a payload without setting the value for LastName, I am getting the following error.
|
ASP.NET Core Model Validation |
builder.Services.AddControllers(x => { x.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; });
Happy Coding.
In this post let's have a look at this nice attribute JsonExtensionDataAttribute that's available in System.Text.Json.Serialization Namespace.
I had a requirement where I have an integration API that connects a client application with a third-party API. The client application is sending some JSON that needs to be sent to the third-party API as is, and at the same time, within the integration API, I need to intercept and read some values in the JSON. The JSON schema can be huge, and the Integration API doesn't really care about the full JSON schema. So how do we define a POCO class having the properties I really care about and let other properties get deserialized/serialized without any data loss.
Let's go by an example.
Consider the following JSON schema.
string jsonString = """ { "_id": "57d0a0a676f943a4007e1525", "modified": "2022-09-07T23:20:06.949Z", "title": "Register", "display": "form", "type": "form", "name": "register", "path": "register", "components": [ { "label": "First Name", "key": "firstName", "type": "textfield", "placeholder": "", "prefix": "", "suffix": "", "multiple": false }, { "label": "Last Name", "key": "firstName", "type": "textfield", "placeholder": "", "prefix": "", "suffix": "", "multiple": false } ], "tags": [] } """;
Now let's say, I only care about _id, name and type properties.
I can create a POCO class, something like below.
public class Form { [JsonPropertyName("_id")] public string Id { get; set; } public string Name { get; set; } public string Type { get; set; } }
But then the issue is, upon deserialization, I am going to lose some data. And this is where JsonExtensionDataAttribute comes in handy.
public class Form { [JsonPropertyName("_id")] public string Id { get; set; } public string Name { get; set; } public string Type { get; set; } [JsonExtensionData] public Dictionary<string, object> JsonExtensionData { get; set; } }
Now when I deserialized the jsonString to Form what's going to happen is, the properties with matching members will get their values and the properties that do not have a matching member will get added to the JsonExtensionData dictionary.
JsonSerializerOptions jsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; Form form = JsonSerializer.Deserialize<Form>(jsonString, jsonSerializerOptions);
Here if I have a look at the form, it's going to look like this.
|
Deserialization |
And now when I serialize the form, the values in the Dictionary are written back as expected.
string serializedString = JsonSerializer.Serialize(form, jsonSerializerOptions); //{ // "_id": "57d0a0a676f943a4007e1525", // "name": "register", // "type": "form", // "modified": "2022-09-07T23:20:06.949Z", // "title": "Register", // "display": "form", // "path": "register", // "components": [ // { // "label": "First Name", // "key": "firstName", // "type": "textfield", // "placeholder": "", // "prefix": "", // "suffix": "", // "multiple": false // }, // { // "label": "Last Name", // "key": "firstName", // "type": "textfield", // "placeholder": "", // "prefix": "", // "suffix": "", // "multiple": false // } // ], // "tags": [] //}
Isn't it nice?
Happy Coding.
Regards,
Jaliya
In this post let's have a look at one of the newest additions to C#, which is the file access modifier.
For types that are declared with file access modifier, its visibility or scope is only limited to the file in which it's declared.
Consider the below code.
File1.cs
namespace MyNamespace; file class MyClass { public static void MyMethod() { // } }
File2.cs
namespace MyNamespace; file class MyClass { public static void MyMethod() { // } }
Here I have 2 classes with the same name and within the same namespace but in different files. With C# 11.0, this will build just fine. Prior to C# 11.0, we weren't able to do this.
file keyword can be applied only to the following types.
And it's allowed only at the top-level type.
public class MyClass { // Error: Not allowed as MyOtherClass is a nested type file class MyOtherClass { } }
It's very unlikely we will be using this file access modifier during business application development. But wanted to share it, because in case you see it, you know what it is.
More read:
file (C# Reference)
File-local types
Hope this helps.
Happy Coding.
Regards,
Jaliya
using System.Security.Claims; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddAuthentication() .AddJwtBearer(); builder.Services.AddAuthorization(); WebApplication app = builder.Build(); // Configure the HTTP request pipeline. app.UseAuthorization(); app.UseHttpsRedirection(); app.MapGet("/", () => "Hello .NET"); app.MapGet("/me", (ClaimsPrincipal user) => { return user?.Claims .Select(c => new { c.Type, c.Value }) .ToList(); }) .RequireAuthorization(); app.Run();
dotnet user-jwts create
|
dotnet user-jwts create |
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "Authentication": { "Schemes": { "Bearer": { "ValidAudiences": [ "http://localhost:35983", "https://localhost:44310", "http://localhost:5000", "https://localhost:7028" ], "ValidIssuer": "dotnet-user-jwts" } } } }
Add New Item |
|
Add Multiple Items |
|
Files Created |
In this post let's see how easy it is to call REST API secured with Azure AD (or Azure AD B2C).
First, we need to select the Authentication type as Active Directory OAuth.
Then it's just a matter of entering the required information.
Active Directory OAuth |
Happy Coding.