Home > other >  ASP.NET - How To Return Both A Web Response And A View?
ASP.NET - How To Return Both A Web Response And A View?

Time:05-25

I've got a servers controller with an action along the lines of ...

[ApiController]
[Route("[controller]")]
[Consumes("application/json")]
public class ServersController : Controller
{
    public ServersController(IMemoryCache memoryCache) => Cache = memoryCache;

    private IMemoryCache Cache { get; }

    [HttpGet(Name = "Get Servers")]
    public IActionResult GetServers()
        => Ok(Cache.Get<List<ServerGetDTO>>(Context.ServerList));
}

... and I've also got a razor page along the lines of ...

@page "/servers"

<PageTitle>Get Servers</PageTitle>

<h1>Gets The Servers (Only Via Response, For Now)</h1>

I'm adding the razor/blazor stuff ...

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapRazorPages());
app.MapBlazorHub();

... but when I navigate to https://.../servers I'm not getting the JSON response that I'm expecting. The expectation is that navigating to the page issues a Get request to the endpoint and then I would both get the view to render on the front-end and also the list of servers as JSON as the response for the Get call.

What am I doing wrong?

UPDATE #1: After having added Blazor on top of my API, I've noticed now that Swagger returns HTML when calling the https://.../servers endpoint, so the HTML document and the JSON response seem to be mutually-exclussive. I'm almost sure I'm missing something, I'll keep investigating.

UPDATE #2: OK, I've figured it out. Now that I know what the problem was, this question, in hindsight, feels silly. This is my first Blazor experiment, and now I know that I've started with a misunderstanding of the technology at an architectural level. Basically, I've bolted onto my already existing API a Blazor Server project, whereas, in fact I should have used a Blazor WASM project instead. Now that I've replaced Blazor Server with Blazor WASM, everything works exactly as expected!

CodePudding user response:

If you want to bolt on a front-end to an already existing API, make sure you're adding Blazor WASM, not Blazor Server.

  • Related