How to call ReadJsonAsync() from static class to another class

I have a static helper class which reads a Json file, which I need to call inside another public class and return 200 response code with JSON filepath as response.

JSON is a static file. just I’m trying to learn how to return the response code with JSON file which i read

Code for Helper.cs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public static class Helper
{
public static async Task<string> GetRequestBody(HttpContext httpContext)
{
string body;
if (httpContext.Request.HasFormContentType)
{
body = JsonSerializer.Serialize(httpContext.Request.Form.ToList());
}
else
{
// Create StreamReader And Starting Reading The Request Body.
using var streamReader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, true, 1024, true);
// Assign The Stream Content To The Payload Object
body = await streamReader.ReadToEndAsync();
}
return body;
}
public static async Task Main(string[] args)
{
string filePath = "path/to/your/file.json";
var jsonData = await ReadJsonFileAsync(filePath);
Console.WriteLine(jsonData);
}
public static async Task<string> ReadJsonFileAsync(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fs))
{
return await reader.ReadToEndAsync();
}
}
}
}
</code>
<code>public static class Helper { public static async Task<string> GetRequestBody(HttpContext httpContext) { string body; if (httpContext.Request.HasFormContentType) { body = JsonSerializer.Serialize(httpContext.Request.Form.ToList()); } else { // Create StreamReader And Starting Reading The Request Body. using var streamReader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, true, 1024, true); // Assign The Stream Content To The Payload Object body = await streamReader.ReadToEndAsync(); } return body; } public static async Task Main(string[] args) { string filePath = "path/to/your/file.json"; var jsonData = await ReadJsonFileAsync(filePath); Console.WriteLine(jsonData); } public static async Task<string> ReadJsonFileAsync(string filePath) { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { using (StreamReader reader = new StreamReader(fs)) { return await reader.ReadToEndAsync(); } } } } </code>
public static class Helper
{
  
public static async Task<string> GetRequestBody(HttpContext httpContext)
{
    string body;
    if (httpContext.Request.HasFormContentType)
    {
        body = JsonSerializer.Serialize(httpContext.Request.Form.ToList());
    }
    else
    {
        // Create StreamReader And Starting Reading The Request Body.
        using var streamReader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, true, 1024, true);
        // Assign The Stream Content To The Payload Object
        body = await streamReader.ReadToEndAsync();
    }

    return body;
}
    public static async Task Main(string[] args)
    {
        string filePath = "path/to/your/file.json";
        var jsonData = await ReadJsonFileAsync(filePath);
        Console.WriteLine(jsonData);
    }

    public static async Task<string> ReadJsonFileAsync(string filePath)
    {
        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            using (StreamReader reader = new StreamReader(fs))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
}

Code snippet Employeerecord.cs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class Employeerecord : IEmployeerecord
{
public Task<List<Domain.Models.EmployeeRecordData>> GET_Employeerecorddata(int employeelist, int employeeId)
{
// How to call the ReadJSonFileASync from Helper class here
// also return 200 code with Json filepath response
}
}
</code>
<code>public class Employeerecord : IEmployeerecord { public Task<List<Domain.Models.EmployeeRecordData>> GET_Employeerecorddata(int employeelist, int employeeId) { // How to call the ReadJSonFileASync from Helper class here // also return 200 code with Json filepath response } } </code>
public class Employeerecord : IEmployeerecord 
{
    public Task<List<Domain.Models.EmployeeRecordData>> GET_Employeerecorddata(int employeelist, int employeeId) 
    {
        // How to call the ReadJSonFileASync from Helper class here
        // also return 200 code with Json filepath response
    }
}

8

First you have to make the GET_Employeerecorddata method async, then you can call the Helper.ReadJsonFileAsync method like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class Employeerecord : IEmployeerecord
{
public async Task<List<Domain.Models.EmployeeRecordData>> GET_Employeerecorddata(int employeelist, int employeeId)
{
// Call the ReadJSonFileASync from Helper class
string filePath = "path/to/your/file.json";
string json = await Helper.ReadJsonFileAsync(filePath);
}
}
</code>
<code>public class Employeerecord : IEmployeerecord { public async Task<List<Domain.Models.EmployeeRecordData>> GET_Employeerecorddata(int employeelist, int employeeId) { // Call the ReadJSonFileASync from Helper class string filePath = "path/to/your/file.json"; string json = await Helper.ReadJsonFileAsync(filePath); } } </code>
public class Employeerecord : IEmployeerecord
{
    public async Task<List<Domain.Models.EmployeeRecordData>> GET_Employeerecorddata(int employeelist, int employeeId)
    {
        // Call the ReadJSonFileASync from Helper class
        string filePath = "path/to/your/file.json";
        string json = await Helper.ReadJsonFileAsync(filePath);
    }
}

Also make sure you add the appropriate using statement to include the namespace the Helper.cs class belongs to.

New contributor

BigBoss is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

4

What you are asking is quite broad, but I think I can give minimal information that should get you started.

First of all, looks like you are looking for some endpoint that would return data from the file.

To create such endpoints (HTTP endopints), you need to create web applicaiton, which in .NET you can do by createing one of ASP.NET Core apps. For simplicity we can go with Web API, leaving frontend out of the picture.

So, create new project of type “ASP.NET Core Web API” (with dotnet CLI it would be just dotnet new webapi).

There you will have Program.cs that you will modify in order to define your endpoint, it should look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
</code>
<code>var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now.AddDays(index)), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast") .WithOpenApi(); app.Run(); record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); } </code>
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast =  Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

We will remove all weather related data that comes in template.

Instead, we will define our method to read a file and adjust endpoint to use it. Here are changes:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/get-json-data", () =>
{
var filePath = "path/to/your/file.json";
var jsonData = await Helper.ReadJsonFileAsync(filePath);
return jsonData;
})
.WithOpenApi();
app.Run();
</code>
<code>var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.MapGet("/get-json-data", () => { var filePath = "path/to/your/file.json"; var jsonData = await Helper.ReadJsonFileAsync(filePath); return jsonData; }) .WithOpenApi(); app.Run(); </code>
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/get-json-data", () =>
{
    var filePath = "path/to/your/file.json";
    var jsonData = await Helper.ReadJsonFileAsync(filePath);
    return jsonData;
})
.WithOpenApi();

app.Run();

Useful reference: Tutorial: Create a web API with ASP.NET Core

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật