C
C#2y ago
Waranai

✅ Web things minimal api

after tons of codding i totally forgot what i wanted to do lmao, so problem is - product has click eventhandler, which gets id of product from attribute, how do i send back html page of product and data? or should i send html page first, and after send data based on "6" from localhost/product/6 ?
30 Replies
Waranai
WaranaiOP2y ago
which is most common way?
Pobiega
Pobiega2y ago
... what? You say minimal api, but this is clearly a graphical client of some sort. Blazor? javascript?
Waranai
WaranaiOP2y ago
i mean
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { WebRootPath = "StaticFiles" });

builder.Services.AddDbContext<PetProjContext>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => options.LoginPath = "/login");
builder.Services.AddAuthorization();

var app = builder.Build();

app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", async () => await SendHtml("index"));
app.MapGet("/api/GetProducts", (PetProjContext db) => db.Products.ToList());
app.MapGet("/addproduct", [Authorize] async () => await SendHtml("addproduct"));
app.MapGet("/login", async () => await SendHtml("login"));
app.MapGet("/registration", async () => await SendHtml("registration"));
app.MapGet("/userpdoructs", async () => await SendHtml("userpdoructs"));
app.MapGet("/personal", async () => await SendHtml("personal"));
app.MapGet("/product", async () => await SendHtml("product"));

app.Run();
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { WebRootPath = "StaticFiles" });

builder.Services.AddDbContext<PetProjContext>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => options.LoginPath = "/login");
builder.Services.AddAuthorization();

var app = builder.Build();

app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/", async () => await SendHtml("index"));
app.MapGet("/api/GetProducts", (PetProjContext db) => db.Products.ToList());
app.MapGet("/addproduct", [Authorize] async () => await SendHtml("addproduct"));
app.MapGet("/login", async () => await SendHtml("login"));
app.MapGet("/registration", async () => await SendHtml("registration"));
app.MapGet("/userpdoructs", async () => await SendHtml("userpdoructs"));
app.MapGet("/personal", async () => await SendHtml("personal"));
app.MapGet("/product", async () => await SendHtml("product"));

app.Run();
thats my code rn
Pobiega
Pobiega2y ago
and for your routes, product/{id} would make sense
Waranai
WaranaiOP2y ago
problem with product/{id] is, i cant send html file
Pobiega
Pobiega2y ago
Where is SendHtml from?
Waranai
WaranaiOP2y ago
static async Task<IResult> SendHtml(string page)
{
string path = $"Html/{page}.html";
string type = "text/html; charset=utf-8";

byte[] file = await File.ReadAllBytesAsync(path);
return Results.File(file, type);
}
static async Task<IResult> SendHtml(string page)
{
string path = $"Html/{page}.html";
string type = "text/html; charset=utf-8";

byte[] file = await File.ReadAllBytesAsync(path);
return Results.File(file, type);
}
Pobiega
Pobiega2y ago
minimal APIs are primarily for building.. well, APIs
Waranai
WaranaiOP2y ago
my method forgot stry
Pobiega
Pobiega2y ago
not full stack webpages okay, so you're serving static html pages via minimal api endpoints thats not a great idea lol, but okay :p
Waranai
WaranaiOP2y ago
so, rn im putting clicked div's id into cookies and all divs gonna redirect to /product, then onload i will request specific product by id from cookies should i send them as static files? or what
Pobiega
Pobiega2y ago
I'm not really sure exactly what you are trying to do here You're abusing minimal APIs to serve html instead of just JSON, and Im guessing your html pages contain javascript to do interactivity
Waranai
WaranaiOP2y ago
so, ill try to explain
Pobiega
Pobiega2y ago
I'd probably make a normal javascript frontend application and serve that via static files and just have a normal json-serving API with that yeah this is some cursed homebrew stuff 😄 You probably can make it work, but its gonna get funky
Waranai
WaranaiOP2y ago
incase "/" im doing that,
Waranai
WaranaiOP2y ago
window.addEventListener("load", async () => {
const cookieName = ".AspNetCore.Cookies";
await FillProducts();

if (document.cookie.includes(cookieName)) {
ButtonLoged();
}
else {
ButtonNotLoged();
}
});
window.addEventListener("load", async () => {
const cookieName = ".AspNetCore.Cookies";
await FillProducts();

if (document.cookie.includes(cookieName)) {
ButtonLoged();
}
else {
ButtonNotLoged();
}
});
async function FillProducts() {
const response = await fetch("/api/GetProducts", {
method: "GET",
headers: { "Accept": "application/json" }
})

if (!response.ok)
console.error();

const data = await response.json();
data.forEach(async product => {
const prod = `
<div class="product-image">
<img src="${product.image}" alt="product-image">
</div>
<div class="product-info">
<p class="title">${product.title}</p>
<p class="pric">${product.price}$</p>
</div>`;

const div = document.createElement("div"); ``
div.classList.add("product");
div.setAttribute("data-product", product.id);
div.insertAdjacentHTML("beforeend", prod);

div.addEventListener("click", () => {
const productId = div.getAttribute("data-product");

const now = new Date();
const expirationTime = new Date(now.getTime() + 15000);
const expires = expirationTime.toUTCString();

document.cookie = `productId=${productId}; expires=${expires};`;
window.location.href = `/product`;
});

document.querySelector("[data-products]").appendChild(div);
});
};
async function FillProducts() {
const response = await fetch("/api/GetProducts", {
method: "GET",
headers: { "Accept": "application/json" }
})

if (!response.ok)
console.error();

const data = await response.json();
data.forEach(async product => {
const prod = `
<div class="product-image">
<img src="${product.image}" alt="product-image">
</div>
<div class="product-info">
<p class="title">${product.title}</p>
<p class="pric">${product.price}$</p>
</div>`;

const div = document.createElement("div"); ``
div.classList.add("product");
div.setAttribute("data-product", product.id);
div.insertAdjacentHTML("beforeend", prod);

div.addEventListener("click", () => {
const productId = div.getAttribute("data-product");

const now = new Date();
const expirationTime = new Date(now.getTime() + 15000);
const expires = expirationTime.toUTCString();

document.cookie = `productId=${productId}; expires=${expires};`;
window.location.href = `/product`;
});

document.querySelector("[data-products]").appendChild(div);
});
};
so
Pobiega
Pobiega2y ago
mhm.
Waranai
WaranaiOP2y ago
onload i request all data and create divs with it
Pobiega
Pobiega2y ago
it kinda seems like you are re-inventing MVC, but in minimal APIs
Waranai
WaranaiOP2y ago
i mean i can make it work with cookies just wanted to clarify, maybe here is a better way looks like i had to wait till mvc course lmao
Waranai
WaranaiOP2y ago
so, rn when i click to div, im redirecting to default product page, without {id}, and have id in cookies, so onload i will request product from db by id
Pobiega
Pobiega2y ago
the thing is, you're not really doing serverside rendered html here, you're just serving static html with vanilla JS to provide interactivity but why are you putting stuff in cookies? just redirect to product/{id} dont abuse cookies :p
Waranai
WaranaiOP2y ago
there was other problem with loading css and js from static files
Pobiega
Pobiega2y ago
I just want you to be aware that what you are doing is... uh.. extremely unorthodox this is NOT how you build webpages normally that said, you can absolutely keep doing you for learning but I dont see the point of your "SendHtml" routes at all tbh serve your entire frontend as static files, and have only api routes in the BE
Waranai
WaranaiOP2y ago
so, incase of index.html is in staticfiles folder, what i need to do, for user see it? i mean, program starts with "/" path, no? ok i get it
app.UseDefaultFiles();
app.UseDefaultFiles();
Pobiega
Pobiega2y ago
yep!
Waranai
WaranaiOP2y ago
it works with index page, but with different pages still need extension name
Waranai
WaranaiOP2y ago
Hmm
Pobiega
Pobiega2y ago
well, you could fix that easily just move your products.html to /products/index.html but tbh, I think you'd benefit greatly from picking up a real frontend app framework or just find some javascript routing library, Im sure something like that exists or move to full on serverside rendered html, using razor pages or MVC
Waranai
WaranaiOP2y ago
yeah looks like its the way ill do this thing abusing cookies but new projecs will be on mvc/razor pages thx for helping anywa 🙂

Did you find this page helpful?