1
votes

I've created my first Blazor Server app, a general form that we wish to use for multiple websites. Each will redirect to this centralized contact type form. We need to know which site the user was directed from. I need to pass that URL along with the generated email and I'd like to use it as a return to website button.

I'm not sure if I should capture this in the controller, in the shared _Layout or in the form component.

1
You can capture it wherever you like, wherever it's easier for you to manage the procedure you were talking about. This is not the question you should ask, I believe. I guess your question should be how to retrieve the calling Url, right ? Or perhaps you know that part of the issue... - enet

1 Answers

2
votes

It's a common belief that you can't access the HttpContext from inside a Blazor-Server app but thats not true, at least, not exact. The point here is that the blazor app behaves like a single page application so, the only moment you can "catch" the HttpContext is when the user hits the endpoint that serves your app or, in other words, when user access to the "_Hosts.cshtml" PAGE (or whatever you have defined, if you override the defaults).

From that point on, the routes you're observing in the browser's address bar are not real urls, but only indications of where the user is inside your app. They not exist on the site, only locally in the user's browser (he can't store links to them on his browser...).

So, the point here is "capturing" the HttpContext on the initial call to the Apps page and store the info you need in a service or passing it along as a parameter to other/s component/s. Make this:

  1. Open your _Host.cshtml file. There you should have access to the HttpContext object, since it is a "real" page. (if not, then add the namespace, put the @using Microsoft.AspNetCore.Http directive on top)

  2. Capture the data you want and pass it to the blazor app as parameters, like this:

    <component type="typeof(App)" render-mode="Server" param-Referer="@(HttpContext.Request.Headers["Referer"]?.ToString() ?? "")" />
    
  3. Create a parameter inside your App.razor to receive the data:

        [Parameter]
        public string? Referer { get; set; }
    
  4. Later on, you can store it on a service, or pass it along, as parameter, cascading parameter, or whatever you want...

Hope it helps. Cheers!