log json calls to API Rest services from an application console

Viewed 42

I need to log requests in json format of all Rest calls, the peculiarity is that I am in a normal Application Console in .net Core 6.0.

Example:

            //class with JsonProperty
            MyClass body = new MyClass ();

            HttpClient client = new HttpClient();
            var request_ = new System.Net.Http.HttpRequestMessage();
            System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings = new Lazy<Newtonsoft.Json.JsonSerializerSettings>();

            var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value));
            content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
            request_.Content = content_;

            request_.Method = new System.Net.Http.HttpMethod("POST");
            request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
            var url_ = "url of request";
            request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
            //I need to capture the json string which is sent in the following call
            var response_ = client.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, System.Threading.CancellationToken.None).ConfigureAwait(false);

How can I capture the calls in json format made by the SendAsync method? is there any way to do this in global mode? I remember that I am in an application console and not in a web api application.

For Asp.Net core 6 you can this:

using Microsoft.AspNetCore.HttpLogging;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpLogging(logging =>
{
    logging.LoggingFields = HttpLoggingFields.All;
    logging.RequestHeaders.Add("sec-ch-ua");
    logging.ResponseHeaders.Add("MyResponseHeader");
    logging.MediaTypeOptions.AddText("application/javascript");
    logging.RequestBodyLogLimit = 4096;
    logging.ResponseBodyLogLimit = 4096;

});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}

app.UseStaticFiles();

app.UseHttpLogging(); 

app.Use(async (context, next) =>
{
    context.Response.Headers["MyResponseHeader"] =
        new string[] { "My Response Header Value" };

    await next();
});

app.MapGet("/", () => "Hello World!");

app.Run();

For .Net Core 6 Console Application?

0 Answers
Related