Ok, I looked on StackOverflow and google and didn't found any solution.What I read on web is that calling a Controller from a Razor page is BAD and it said we need to rethink our programming.
Fine, I accept that. But I didn't find any other ways.Here the problem:
- I got a .NET8 Blazor/Razor app with Microsoft Identity
- The same Web App also have Api Controllers
- One of theses controller can querying the Db for a webLink (stored) based on a stringId.Example: StringId is E4A1 and it represent: https://Google.ca/When querying the Api for "E4A1", it return "https://Google.ca/"
- Querying the Controller (API) work fine, I need to be able to Query from a Razor page.
Here what I tried.
- From Razor page, I add:
@inject ApplicationDbContext _DbContext- [Link] Model look like this
public class LinkModel { [Key] public int Id { get; set; } [Required] [MaxLength(8)] public string StringId { get; set; } = ""; [MaxLength(512)] public string Url { get; set; } = ""; }- From Razor page @code section, I have a function trying to call
string strId = "E4A1"; LinkModel? objTable = await _DbContext.DbLinks.FirstOrDefaultAsync(w => w.StringId == strId);VsStudio complain that FirstOrDefaultAsync DOES NOT EXIST in that context.
So what I did is, inside the LinkController, I created a fonction:
public static class LinkFunctions { public static async Task<string> GetUrlX(ApplicationDbContext objDbContext, string strHex32Id) { LinkModel? objTable = await objDbContext.DbLinks.FirstOrDefaultAsync(w => w.StringId == strHex32Id); return objTable.Url; } }This is the exact same code but in the Controller
and I call it from my Razor page like this:
string strId = "E4A1"; string strUrl = await LinkFunctions.GetUrlX(_DbContext, strId);and that Work...
Here the questions:
- Why it isn't working from the Razor page (same code) ?
- Why is it bad to call the controller from the Razor page
- How do I fix it in a better way ?
Thanks