I’m trying to get a custom favicon loaded for my page based on information gathered in the codebehind. I have a public string property ClientFavicon
that is being populated correctly in the codebehind for my aspx file, but it seems I’m unable to use it. Here’s what my aspx file looks like:
<%@ Page Language="c#" CodeBehind="page.aspx.cs" AutoEventWireup="True" Inherits="project.namespace" EnableViewState="True" Async="true" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8">
<link href="<%=ClientFavicon%>" rel="shortcut icon" type="image/x-icon" />
...
other head elements
...
</head>
<body>
...
other page elements
...
</body>
</html>
And the codebehind:
namespace project.namespace
{
public class myclass
{
public string ClientFavicon { get; set; }
private void Page_Load(object sender, EventArgs e)
{
...
other code
...
LoadClientFavicon();
}
private void LoadClientFavicon()
{
var clientFolder = "/images/client/";
var favicon = string.Empty;
if (HttpContext.Current.Session != null)
{
favicon = HttpContext.Current.Session[Global.SESSION_GLOBAL_CLIENT_FAVICON] != null
? HttpContext.Current.Session[Global.SESSION_GLOBAL_CLIENT_FAVICON].ToString()
: "favicon.ico";
ClientFavicon = clientFolder + favicon;
}
}
}
}
However when I run this, I get no favicon and the following 400 error in the browser devtools Network tab:
https://website.url/aspxpage/%3C%=ClientFavicon%%3E
So it looks to me like it doesn’t recognize what’s in the link as a variable, just as text.
For the favicon link element, I’ve tried with no success: using single quotes instead of double, removing the equals sign, and adding runat="server"
.
I’ve also tried placing a snippet <% var test = ClientFavicon; %>
at the top of the aspx page and set a breakpoint, the test
variable has the right data. I was also unable to get test
to work in the href with all of the syntax trial and error above.
Lastly I’ve tried moving the method populating ClientFavicon out of the codebehind and into a <% %>
block at the top of the page before the <head>
tag and using a variable there, but I get the same result.
I’ve looked at a handful of other StackOverflow posts related to this and I’m not sure what else to try or if I’m missing something.
2
Answers
A coworker found that wrapping the
link
in an asp placeholder would work Since the<head>
hasrunat="server"
:Try changing the link like this:
And then including the quotes as part of the variable:
You might also need to set the entire
link
entity:and then in the code-behind:
And since this is Web Forms where you might be using something too old for string interpolation:
(I find the format placeholders are much more readable than escaped quotes or verbatim strings for including the quote characters, but that’s a personal preference.)