C
C#15mo ago
wwww

✅ 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
wwww
wwwwOP15mo ago
which is most common way?
Pobiega
Pobiega14mo ago
... what? You say minimal api, but this is clearly a graphical client of some sort. Blazor? javascript?
wwww
wwwwOP14mo 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
Pobiega14mo ago
and for your routes, product/{id} would make sense
wwww
wwwwOP14mo ago
problem with product/{id] is, i cant send html file
Pobiega
Pobiega14mo ago
Where is SendHtml from?
wwww
wwwwOP14mo 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
Pobiega14mo ago
minimal APIs are primarily for building.. well, APIs
wwww
wwwwOP14mo ago
my method forgot stry
Pobiega
Pobiega14mo 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
wwww
wwwwOP14mo 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
Pobiega14mo 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
wwww
wwwwOP14mo ago
so, ill try to explain
Pobiega
Pobiega14mo 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
wwww
wwwwOP14mo ago
incase "/" im doing that,
wwww
wwwwOP14mo 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
Pobiega14mo ago
mhm.
wwww
wwwwOP14mo ago
onload i request all data and create divs with it
Pobiega
Pobiega14mo ago
it kinda seems like you are re-inventing MVC, but in minimal APIs
wwww
wwwwOP14mo 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
wwww
wwwwOP14mo 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
Pobiega14mo 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
wwww
wwwwOP14mo ago
there was other problem with loading css and js from static files
Pobiega
Pobiega14mo 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
wwww
wwwwOP14mo 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
Pobiega14mo ago
yep!
wwww
wwwwOP14mo ago
it works with index page, but with different pages still need extension name
wwww
wwwwOP14mo ago
Hmm
Pobiega
Pobiega14mo 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
wwww
wwwwOP14mo 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 🙂
Want results from more Discord servers?
Add your server