Do variable check only once in blazor - c#

I have several razor pages I want to do checks on using the current URL value.
They currently all have in their #code{} block URLs like:
Razor Page 1: MyNavigationManager.NavigateTo("sample_domain/sub_page_1?i=" + variable, forceLoad: true);
Razor Page 2: MyNavigationManager.NavigateTo("sample_domain/sub_page_2?i=" + variable, forceLoad: true);
Razor Page 3: MyNavigationManager.NavigateTo("sample_domain/sub_page_3?i=" + variable, forceLoad: true);
I would like to remove the sample_domain/ part if the URL has localhost in it.
So I have seen here that I can get the current urls by Injecting before using it on .razor pages #inject NavigationManager MyNavigationManager and using MyNavigationManager.Uri to get the url.
Now I implemented it doing the following in each of the razor pages code block:
//check if the url has localhost
string domain_url = MyNavigationManager.Uri.ToString().Contains("localhost") ? "" : "/sample_domain";
MyNavigationManager.NavigateTo($"{domain_url}/sub_page_1?i=" + variable, forceLoad: true);
But now I only want to do the check once, and set the variable there, e.g. the domain_url. Then use that variable in the different razor pages without explicitly checking and setting it in each page. Maybe something like a global variable? session? But not sure how to go about that? Thanks.

You can call a method in a service to do that for you. For example, create a service MyService.cs, and have a method like GetUrl
public string GetUrl(string nav_url)
{
return nav_url.ToString().Contains("localhost") ? "" : "/sample_domain";
}
Inject the service #inject MyService MService in _Imports.razor, also add the service in the Program.cs file builder.Services.AddSingleton<MyService>(); then call the method like:
MyNavigationManager.NavigateTo($"{MService.GetUrl(MyNavigationManager.Uri)}/sub_page_1?i=" + variable, forceLoad: true);

Related

LinkGenerator returns null

I defined a Blazor page with the following directive:
#page "section/{name}/details"
and I'm trying to generate a link to it from another page using the LinkGenerator:
var absoluteUri = this.LinkGenerator.GetUriByPage(this.HttpContextAccessor.HttpContext, "/section/{name}/details", values: new { name = "mysection" });
Anyway, absoluteUri is always null.
What am I missing?
The LinkGenerator is used for generating URLs for the server-side endpoint routing. It is able to generate links to endpoints that are known to the endpoint routing mechanism, i.e. things like MVC actions, Razor pages, or named routes.
Blazor pages are part of the client-side routing mechanism though (yes, even with server-side Blazor), and as such they don’t take part in the server-side routing mechanism. That’s why I don’t believe that the LinkGenerator could possibly generate URLs for client-side routing.
Unfortunately, I am not aware of an alternative that uses Blazor routing. So I think you will have to generate the URL manually, or build your own tool to generate the link. Since you are using server-side Blazor, you do have access to the HttpContext, so you can use that to generate an absolute URL. Something like this would probably work:
#inject IHttpContextAccessor httpContextAccessor
…
#code {
string GetUrl(string sectionName)
{
var request = httpContextAccessor.HttpContext.Request;
return request.Scheme + "://" + request.Host + request.PathBase + $"section/{sectionName}/details";
}
}

Razor cshtml getting parameters from another cshtml

I am new to C# and Razor v3.
I have a php web app that I am trying to convert to ASP.NET. I decided, mainly due to ease, to use Razor. What I am making is a Single Page App.
The way I have it laid out in PHP is via 3 php files, 1 of which essentially passes the variable values to the main index.php like so, for example
vars.php
if (isset($_GET["lang"])) {
$lang = mb_strtolower($_GET["lang"]);
} else {
$lang = "el";
}
and this is how my index.php uses that variable
<html lang=<?php echo "\"".$lang."\"";if($page2go===1) {echo " itemscope itemtype=\"http://schema.org/Article\"";}?>>
Now, everytime index.php is called, I call on vars.php by using
<?php require_once('./scripts/vars.php');?>
This is how my values are passed into my index.php.
I have found I can do the similar by including my if statements and variable delcarations at the top of my index.cshtml. Like so
#{
var lang = "";
if (!String.IsNullOrEmpty(Request.QueryString["lang"]))
{
var interior = Request.QueryString["lang"];
interior.ToLower();
lang = interior;
}
else
{
lang = "el";
}
}
Now I perform a LOT of if operations like that, making my index.cshtml an absolute mess.
Is there a way to pass the variable values, like I do in php by including vars.php?
Thanks a lot for your time.
You should recreate your one-page application to an MVC application.
All the request processing (and other complex logic) will take place in the controller action.
The controller action will in turn pass all variables that you need to the view that you have created.

MVC Url.Content with javascript local variable

I have problem with this:
var id=5;
var el = $("MainPhotoHolder");
el.attr("src", '#Url.Content("~/Page/GetImage/" + id)');
id is a local javascript variable, but it gives me an error saying that is not in the context. My question is how do i point out that it should be a javascript variable and not a c# one ...?
You cannot mix JavaScript and Razor in this way. Razor does not have any reference to it so it cannot use it to generate your link. Try this:
el.attr("src", '#Url.Content("~/Page/GetImage/")' + id);
You might have to use "Url.Action" if you're serving the images from a controller rather than a static repository.

How to send debug text from C# class to ASP.NET page

I am working on a C# class that is a part of my ASP.Net Web Site.
Is there a simple way to output some log/debugging text to the top of the page. My class does NOT inherit from Page. I want to display variable values, etc.
The class represents an Exam object that I use in some of my aspx pages. The variables that I want to display are private and therefore inaccessible to my aspx pages.
Anywhere in the context of an http request you can reach the current executing page as follows.
Page page = HttpContext.Current.Handler as Page;
You are free to cast to your own page type. So you can write debug info to labels, textboxes etc.
you can just do this
HttpContext.Current.Response.Write("your message goes here");
or write a helper method
public static void writeOut(string message) {
HttpContext.Current.Response.Write(message);
}
You can try with Response.Write method
var pathOfYourLog = "";
var log = File.ReadAllLines(pathOfYourLog);
YourHttpContext.Response.Write(log);

Forcing SSL (https) on a page by page basis

How can I set up my page load event in my code behind to redirect to an url that has an https prefix? I would need it to work with urls that have query strings attached too.
It's one thing to construct a link that goes straight to the https page, but I don't want the user to be able to manually change it to an http page.
Also I don't want to do it with javascript because it might be turned off.
I'm guessing a regular expression?
We mark our SSL Required pages with a special attribute ForceSslAttribute. Then we have a HttpModule that pulls down the current page's class and inspect it's attributes.
If the attribute is present on the page, it takes the exact url that was passed and changes the protocol from http to https then calls a redirect.
There's probably a bit simpler way of doing it, but that's how it's done for us.
Attribute:
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public sealed class ForceSslAttribute : Attribute
{
// Marker Attribute
}
Page Example (CodeBehind):
[ForceSsl]
public partial class User_Login : Page
{
//...
}
You can figure out the type of the page like this:
HttpContext.Current.CurrentHandler.GetType()
All Page's implement IHttpHandler and when you're visiting a page, it'll work.
The cool part about this method is you can mark anything that's an IHttpHandler and it'll force the redirect too :)
Add this at the top of your Page_Load
if (Request.ServerVariables["HTTPS"] != "ON")
{
Response.Redirect("https://" + Request["HTTP_HOST"] + Request.RawUrl);
}
I use the following in Global.asax Application_BeginRequest
If needsSSL <> Request.IsSecureConnection Then
If needsSSL Then
Response.Redirect(Uri.UriSchemeHttps + Uri.SchemeDelimiter + Request.Url.Host + Request.Url.PathAndQuery, True)
Else
Response.Redirect(Uri.UriSchemeHttp + Uri.SchemeDelimiter + Request.Url.Host + Request.Url.PathAndQuery, True)
End If
End If
There is an IIS7 module for URL rewriting. Very handy, but you need access to the IIS and it requires some time to learn how to write the rules. A simple http->https rule is a matter of seconds.
Just be careful because any rules you add will be stored in your web.config, so don't delete/override it or you will have to write them again.
Forcing SSL using ASP
To force SSL using ASP, follow these steps:
Click Start, click Run, type Notepad, and then click OK.
Paste the following code into a blank Notepad document. On the File menu, click Save As, and then save the following code in the root of your Web server as an include file named ForceSSL.inc:
<%
If Request.ServerVariables("SERVER_PORT")=80 Then
Dim strSecureURL
strSecureURL = "https://"
strSecureURL = strSecureURL & Request.ServerVariables("SERVER_NAME")
strSecureURL = strSecureURL & Request.ServerVariables("URL")
Response.Redirect strSecureURL
End If
%>
For each page that requires SSL, paste the following code at the top of the page to reference the include file from the previous step:
<%#Language="VBSCRIPT"%>
<!--#include virtual="/ForceSSL.inc"-->
When each page is browsed, the ASP code that is contained in the include file detects the port to determine if HTTP is used. If HTTP is used, the browser will be redirected to the same page by using HTTPS.

Categories

Resources