Blazor Favicon Setup: A Practical Step-by-Step Guide
If your Blazor app works but its tab shows a generic document icon, the cause is usually a missing static file or head link. A reliable Blazor favicon needs both: an asset served by the app and a rel='icon' link in the document head. The same approach works across Blazor's common hosting models.
Prerequisites
You need an existing Blazor project, its .NET SDK, and a square logo. If your source is PNG, use Mzu favicondl to create SVG, ICO, and PNG variants.
Blazor Web App: find the shared document in Components/App.razor.
Standalone WebAssembly: find the document in wwwroot/index.html.
Hosted WebAssembly: identify the client index and the server project that publishes it.
1. Identify the template and its head file
Open the file named above and inspect its head. In a Blazor Web App, edit Components/App.razor; in standalone WebAssembly, edit wwwroot/index.html. In hosted WebAssembly, edit the client index, but verify that the deployed server serves its assets. If an older template uses Pages/_Host.cshtml, edit that document instead. Keep the global icon out of ordinary page components, where it may apply to only one route.
Place these files under wwwroot so they publish as static web assets. We recommend a scalable SVG, an ICO containing 16, 32, and 48 px images, and an optional 180×180 PNG for touch shortcuts. Use square artwork with padding and remove tiny text; it disappears at 16 px. Convert or package the files with Mzu favicondl.
3. Add the Blazor favicon links to the document head
Add the global links inside the same head that contains the base URL and stylesheet links:
These relative URLs follow the app's base path instead of assuming the domain root. The HTML Standard's rel='icon' definition describes an external resource icon; type and sizes describe the file. Keep the ICO link as a fallback, and define one global set rather than repeating it in every component.
4. Update WebAssembly projects
For standalone WebAssembly, paste the same links into the head of wwwroot/index.html. For hosted WebAssembly, add them to the client index, publish the solution, and inspect the server output:
dotnet publish -c Release
Confirm the published wwwroot contains the favicon folder. If not, copy it into the host's wwwroot or adjust static-asset publishing. The client index can work while an icon still returns 404.
5. Check static-file serving
If a direct icon request returns 404, inspect Program.cs for app.UseStaticFiles() or an existing static-assets endpoint mapping. If neither exists, insert this before routing and endpoint registration:
app.UseStaticFiles();
Do not replace the pipeline or duplicate existing static-asset handling. Pages can render while /favicon/favicon.ico fails when this step is missing. Standalone WebAssembly does not need ASP.NET Core middleware because its published output is a static site.
6. Verify the file and the browser tab
Run the project with dotnet run, replace 5000 below with the printed port, and request both files directly:
Each response should return 200 and an image content type. View the page source and confirm the link elements are in the head. If the HTML is correct but the tab shows the old icon, open a new tab or private window and inspect the Network panel. A normal hard refresh may not replace an already cached icon.
Repeat the check on the deployed URL. Localhost success does not prove production uses the same base path or serves the same files.
Common pitfalls
404 on the icon: confirm the file is under wwwroot/favicon, the relative path matches, and static files are mapped.
Works locally, fails in a subpath: avoid a root-only /favicon/... URL when Blazor's base URL points elsewhere; keep the links relative as shown.
Duplicate or stale icons: remove the template's old favicon link, then use a fresh tab. See the localhost favicon troubleshooting guide for a focused checklist.
One format fails: export a valid, self-contained SVG and retain a multi-size ICO fallback. External styles or resources may make an SVG unreliable as a favicon.
Conclusion
Match the hosting model to the head file, put assets under wwwroot, and declare relative global URLs. Test the files directly before debugging the tab. For nonstandard server setup, see the broader ASP.NET Core favicon setup reference.
如果 Blazor 应用能够正常运行,但浏览器标签页里显示的还是默认文档图标,通常是因为缺少 static file,或文档 head 中没有对应的 link。要让 Blazor favicon 稳定生效,两者都需要:应用提供图标资源,文档 head 中包含 rel='icon' 链接。Blazor 常见的各种 hosting model 都适用这套做法。
根据 hosting model 配置 head 文件,将资源放在 wwwroot 下,并用相对路径声明全局 URL。调试标签页之前,先直接测试这些文件。对于非标准服务器配置,可参阅更完整的 ASP.NET Core favicon 设置参考。
Blazor アプリが動作しているのに、タブに表示されるアイコンが一般的なドキュメントアイコンなら、原因は通常、static file または head 内の link が欠けていることです。確実に機能する Blazor favicon には、次の両方が必要です。アプリが配信するアセットと、document head 内の rel='icon' link です。同じアプローチは Blazor の一般的なホスティングモデルでも使用できます。
hosting model と head ファイルが適合するようにし、アセットを wwwroot の下に配置して、相対的なグローバル URL を宣言します。タブの動作を調査する前に、各ファイルを直接テストしてください。標準外のサーバー構成については、より一般的なASP.NET Core favicon setupのリファレンスを参照してください。
Blazor 앱은 정상적으로 동작하지만 탭에 일반 문서 아이콘만 표시된다면, 대개 정적 파일이나 문서의 head에 연결된 링크가 빠져 있기 때문입니다. 안정적인 Blazor favicon을 적용하려면 앱이 제공하는 asset과 문서 head에 삽입한 rel='icon' 링크가 모두 필요합니다. 이 방식은 Blazor의 일반적인 hosting 모델 전반에서 동일하게 사용할 수 있습니다.
준비 사항
기존 Blazor 프로젝트, 해당 프로젝트의 .NET SDK, 정사각형 로고가 필요합니다. 원본이 PNG라면 Mzu favicondl로 SVG, ICO, PNG 변형 파일을 만드세요.
Blazor Web App: 공유 문서는 Components/App.razor 파일에서 찾습니다.
Standalone WebAssembly: 문서는 wwwroot/index.html 파일에서 찾습니다.
Hosted WebAssembly: 클라이언트의 index 파일과 해당 파일을 게시하는 server 프로젝트를 확인합니다.
1. 템플릿과 head 파일 확인
위에서 확인한 파일을 열고 head를 살펴보세요. Blazor Web App은 Components/App.razor를 수정하고, Standalone WebAssembly은 wwwroot/index.html을 수정합니다. Hosted WebAssembly에서는 client index를 수정하되, 배포된 서버가 해당 asset을 실제로 제공하는지도 확인해야 합니다. 이전 템플릿에서 Pages/_Host.cshtml를 사용한다면 대신 그 문서를 수정합니다. 전역 아이콘 설정은 일반 page component에 넣지 마세요. 해당 component는 특정 route에만 적용될 수 있습니다.
이 파일들을 wwwroot 아래에 배치하면 정적 web asset으로 게시됩니다. 확장 가능한 SVG, 16, 32, 48 px 이미지를 담은 ICO, touch shortcut용 180×180 PNG를 권장하며, PNG는 선택적으로 사용할 수 있습니다. 로고 그래픽은 정사각형에 여백을 두고 작은 글자는 제거하세요. 16 px에서는 작은 글자가 보이지 않습니다. 파일 변환과 패키징에는 Mzu favicondl을 사용하세요.
3. 문서 head에 Blazor favicon 링크 추가
base URL과 stylesheet 링크가 들어 있는 동일한 head 안에 전역 링크를 추가합니다.
이 상대 URL은 도메인 루트를 가정하는 대신 앱의 base path를 따릅니다. HTML Standard의 rel='icon' 정의는 외부 리소스 아이콘을 설명하며, type과 sizes는 파일을 설명합니다. ICO 링크는 fallback으로 유지하고, 모든 component마다 반복하지 말고 하나의 global set으로 정의하세요.
4. WebAssembly 프로젝트 업데이트
독립형 WebAssembly에서는 동일한 링크를 wwwroot/index.html의 head에 붙여 넣으세요. hosted WebAssembly에서는 client index에 링크를 추가한 다음 solution을 게시하고 server output을 확인합니다.
dotnet publish -c Release
게시된 wwwroot에 favicon 폴더가 포함되어 있는지 확인하세요. 그렇지 않다면 해당 폴더를 host의 wwwroot에 복사하거나 static-asset publishing 설정을 조정하세요. client index가 정상적으로 표시되더라도 아이콘은 404를 반환할 수 있습니다.
5. 정적 파일 제공 확인
아이콘을 직접 요청했을 때 404가 반환된다면 Program.cs에서 app.UseStaticFiles() 또는 기존 static-assets endpoint mapping을 확인하세요. 둘 다 없다면 routing 및 endpoint 등록보다 앞에 다음 코드를 삽입하세요.
app.UseStaticFiles();
기존 pipeline을 교체하거나 static-asset 처리를 중복해서 추가하지 마세요. 이 단계를 빠뜨리면 페이지가 렌더링되더라도 /favicon/favicon.ico 요청은 실패할 수 있습니다. standalone WebAssembly은 게시된 output이 정적 사이트이므로 ASP.NET Core middleware가 필요하지 않습니다.
6. 파일과 브라우저 탭 확인
dotnet run으로 프로젝트를 실행한 다음, 아래 명령의 5000을 출력된 port로 바꾸고 두 파일을 직접 요청하세요.
각 응답은 200을 반환하고 image content type을 제공해야 합니다. 페이지 소스를 확인해 link 요소가 head 안에 있는지 확인하십시오. HTML이 올바르지만 탭에 기존 아이콘이 계속 표시된다면 새 탭이나 private window를 열어 Network panel을 점검하십시오. 일반적인 hard refresh로는 이미 캐시된 아이콘이 바뀌지 않을 수 있습니다.
배포된 URL에서도 동일한 검사를 반복하십시오. localhost에서 정상 동작한다고 해서 production이 동일한 base path를 사용하거나 동일한 파일을 제공한다는 뜻은 아닙니다.
로컬에서는 작동하지만 subpath에서는 실패: Blazor의 base URL이 다른 위치를 가리킬 때는 root-only /favicon/... URL을 사용하지 마십시오. 표시된 것처럼 link를 relative로 유지하십시오.
favicon이 중복되거나 오래된 파일이 남아 있음: 템플릿의 기존 favicon link를 제거한 다음 새 탭을 사용하십시오. 자세한 체크리스트는 localhost favicon 문제 해결 가이드를 참고하십시오.
한 가지 format이 실패함: 유효하고 self-contained한 SVG를 export하고 multi-size ICO fallback을 유지하십시오. 외부 styles나 resources를 참조하면 SVG를 favicon으로 사용하는 것이 불안정할 수 있습니다.
결론
hosting model을 head file에 맞추고, assets를 wwwroot 아래에 놓고, relative global URL을 선언하십시오. 탭을 디버깅하기 전에 각 파일을 직접 테스트하십시오. 비표준 server setup을 사용하는 경우 더 자세한 ASP.NET Core favicon 설정 참고 문서를 보십시오.
Si tu aplicación Blazor funciona pero su pestaña muestra el icono genérico de un documento, normalmente se debe a que falta un archivo estático o el enlace del head. Un Blazor favicon fiable necesita ambas cosas: un recurso servido por la aplicación y un enlace rel='icon' en el head del documento. El mismo enfoque funciona en los modelos de hosting habituales de Blazor.
Requisitos previos
Necesitas un proyecto de Blazor ya creado, su .NET SDK y un logotipo cuadrado. Si tu imagen de origen es PNG, usa Mzu favicondl para crear variantes SVG, ICO y PNG.
Blazor Web App: localiza el documento compartido en Components/App.razor.
Standalone WebAssembly: localiza el documento en wwwroot/index.html.
Hosted WebAssembly: identifica el index del cliente y el proyecto del servidor que lo publica.
1. Identifica la plantilla y su archivo head
Abre el archivo mencionado anteriormente y revisa su head. En una Blazor Web App, edita Components/App.razor; en WebAssembly independiente, edita wwwroot/index.html. En WebAssembly hospedado, edita el index del cliente, pero comprueba que el servidor desplegado sirva sus assets. Si una plantilla más antigua usa Pages/_Host.cshtml, edita ese documento en su lugar. Mantén el icono global fuera de los componentes de página normales, ya que allí podría aplicarse solo a una ruta.
Coloca estos archivos dentro de wwwroot para que se publiquen como static web assets. Recomendamos un SVG escalable, un ICO que contenga imágenes de 16, 32 y 48 px y un PNG opcional de 180×180 para los accesos táctiles. Usa una ilustración cuadrada con margen y elimina el texto pequeño: desaparece a 16 px. Convierte o empaqueta los archivos con Mzu favicondl.
3. Añade los enlaces del Blazor favicon al head del documento
Añade los enlaces globales dentro del mismo head que contiene la URL base y los enlaces a las hojas de estilos:
Estas URL relativas siguen la ruta base de la aplicación en lugar de dar por supuesta la raíz del dominio. La definición de rel='icon' del HTML Standard especifica un icono almacenado en un recurso externo; type y sizes describen el archivo. Mantén el enlace al ICO como fallback y define un conjunto global único en lugar de repetirlo en cada componente.
4. Actualiza los proyectos WebAssembly
Para WebAssembly standalone, pega los mismos enlaces en el head de wwwroot/index.html. Para WebAssembly hosted, añádelos al archivo index del cliente, publica la solución y revisa la salida del servidor:
dotnet publish -c Release
Comprueba que el wwwroot publicado contenga la carpeta favicon. Si no, cópiala en el wwwroot del host o ajusta la publicación de archivos estáticos. El index del cliente puede funcionar aunque un icono siga devolviendo 404.
5. Comprueba cómo se sirven los archivos estáticos
Si la solicitud directa de un icono devuelve 404, revisa Program.cs en busca de app.UseStaticFiles() o de un mapeo existente de endpoints para archivos estáticos. Si no existe ninguno de los dos, inserta esto antes del enrutamiento y del registro de endpoints:
app.UseStaticFiles();
No reemplaces el pipeline ni dupliques la gestión existente de archivos estáticos. Cuando falta este paso, las páginas pueden renderizarse mientras /favicon/favicon.ico falla. WebAssembly standalone no necesita middleware de ASP.NET Core porque su salida publicada es un sitio estático.
6. Verifica el archivo y la pestaña del navegador
Ejecuta el proyecto con dotnet run, sustituye 5000 por el puerto que aparece en pantalla en los comandos siguientes y solicita directamente los dos archivos:
Cada respuesta debe devolver 200 y un tipo de contenido de imagen. Consulta el código fuente de la página y confirma que los elementos link están en el head. Si el HTML es correcto pero la pestaña sigue mostrando el icono anterior, abre una pestaña nueva o una ventana privada e inspecciona el panel Network. Una recarga forzada normal puede no reemplazar un icono que ya esté en caché.
Repite la comprobación en la URL desplegada. Que funcione en localhost no demuestra que producción utilice el mismo base path o sirva los mismos archivos.
Problemas habituales
404 en el favicon: confirma que el archivo está en wwwroot/favicon, que la ruta relativa coincide y que los archivos estáticos están mapeados.
Funciona en local, pero falla en una subruta: evita una URL /favicon/... limitada a la raíz cuando la base URL de Blazor apunte a otro lugar; mantén los enlaces relativos como se muestra.
Iconos duplicados u obsoletos: elimina el enlace al favicon antiguo de la plantilla y abre una pestaña nueva. Consulta la guía de resolución de problemas del favicon en localhost para obtener una lista de comprobación específica.
Un formato no funciona: exporta un SVG válido y autocontenido y conserva un ICO de respaldo con varios tamaños. Los estilos o recursos externos pueden hacer que un SVG no sea fiable como favicon.
Conclusión
Ajusta el modelo de hosting al archivo head, coloca los recursos bajo wwwroot y declara URL globales relativas. Prueba los archivos directamente antes de depurar la pestaña. Para una configuración de servidor no estándar, consulta la referencia más amplia sobre la configuración del favicon en ASP.NET Core.
Build a clean favicon set
Convert a square source image into ICO, PNG, and SVG files with Mzu favicondl, then add them using the Blazor steps above.