Blazor 튜토리얼: SEO 친화적인 문화 링크 사용
최근 업데이트 10/11/2024 Blazor Server | VS 2022 | .NET 8 | TablerForNetBlazor 응용 프로그램에서 SEO 친화적인 문화 링크를 사용하는 방법에 대한 이 튜토리얼에 오신 것을 환영합니다. 이 튜토리얼에서는 페이지 URL이 검색 엔진에 적합한지 확인하면서 Blazor 애플리케이션의 문화를 변경하는 방법을 배우게 됩니다. 이렇게 하면 애플리케이션이 검색 엔진에 의해 더 잘 색인화되고 다양한 문화권에 대한 향상된 사용자 경험을 제공할 수 있습니다. 시작해볼까요?
Blazor에서 SEO 친화적인 문화 링크 시작하기
이 튜토리얼에서는 다음 측면의 구현을 다룹니다.
- 응용 프로그램 문화 변경: Blazor 응용 프로그램에서 문화 설정을 수정하는 방법을 알아봅니다.
- 구조화된 URL 스키마: 다양한 문화를 나타내기 위해 URL을 www.ghostlyInc.com/en-US/siteName으로 구성하는 방법을 알아보세요.
- 브라우저 기반 문화 변화: 사용자가 브라우저 설정을 사용하여 문화를 동적으로 변경할 수 있는 방법을 이해합니다.
- 문화권 변경에 대한 오류 처리: 사용자가 지원되지 않거나 잘못된 문화권 링크로 변경하려고 할 때 강력한 오류 처리를 구현합니다.
- SEO 친화적 및 문화별 URL: URL이 검색 엔진에 최적화되고 특정 문화에 맞게 조정되었는지 확인합니다.
- 향상된 검색 엔진 색인 생성: 적절한 문화 현지화 관행을 채택하여 검색 엔진 순위를 높이고 사용자 경험을 향상시킬 수 있습니다.
SEO 친화적인 문화 링크 구현: 코드
이제 Blazor 애플리케이션에서 SEO 친화적인 문화 링크를 가능하게 하는 코드 구현에 대해 알아보겠습니다. 절차의 각 단계를 안내해 드리겠습니다.
이제 Culture Controller가 필요합니다. 이 컨트롤러는 문화가 변경되면 새 페이지로 리디렉션됩니다.
이제 Culture Service와 Culture Controller를 만들었습니다. 다음 단계로 파일을 수정합니다. Progarm.cs
- 문화 서비스 추가
- 목록에서 지원되는 첫 번째 문화로 기본 문화를 설정합니다.
- 콘텐츠 현지화를 위해 지원되는 문화 목록을 추가합니다.
- 사용자 인터페이스 현지화에 대해 지원되는 UI 문화 목록을 추가합니다.
- 구성된 현지화 옵션을 요청 파이프라인에 적용합니다.
- 들어오는 HTTP 요청을 해당 컨트롤러 작업에 매핑합니다.
다음 단계로 파일을 수정합니다. _host.cshtml
- CultureService 주입
- HTML lang 속성 설정
- Body 태그에 Culture 쿠키 설정
다음 단계로 파일을 수정합니다. App.razor
- CultureService 주입
- NavigationManager 주입
- 아래에 표시된 코드 섹션을 코드에 추가합니다.
@inject NavigationManager Navigation
@inject CultureService cultureService
@code {
/// <summary>
/// This section handles redirection to a new culture when the user changes the culture in the browser link.
/// If you don't wish to support this, you can delete this code.
/// By default, it redirects to the current culture if no culture is specified in the link.
/// </summary>
/// <param name="firstRender">Indicates whether this is the initial rendering of the page</param>
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
// Check if the link contains a specified culture
var culture = cultureService.GetCultureFromLink(Navigation.Uri, Navigation.BaseUri);
// If the culture string is null or empty, it's the page's first load. In this case, set the culture from the browser settings.
if (string.IsNullOrEmpty(culture)) culture = CultureInfo.CurrentCulture.Name;
// Check if the culture is supported by the application
if (!cultureService.IsCultureSupported(culture))
{
// Try to set the language contained in the culture
culture = cultureService.HandleUnsupportedCulture(culture);
}
var cultureInfo = new CultureInfo(culture);
// If the current culture differs from the specified culture, set the new culture
if (!CultureInfo.CurrentCulture.Name.Equals(culture))
{
cultureService.SetCulture(cultureInfo);
}
}
}
}
다양한 문화를 테스트하기 위한 새로운 구성 요소 만들기 ChangeCulture.razor
@using System.Globalization
@inject CultureService cultureService
<button @onclick="() => SetCulture(Englisch)"> Englisch</button>
<button @onclick="() => SetCulture(Arabische)"> Arabische</button>
<button @onclick="() => SetCulture(France)"> France</button>
<button @onclick="() => SetCulture(Austria)"> Austria</button>
<button @onclick="() => SetCulture(Germany)"> Germany</button>
@code {
private string Englisch = "en-US";
private string Arabische = "ar-AE";
private string France = "fr-FR";
private string Austria = "de-AT";
private string Germany = "de-DE";
private void SetCulture(string culture)
{
cultureService.SetCulture(new CultureInfo(culture));
}
}
다음 단계로 파일을 수정합니다. MainLayout.razor
- CultureService 주입
- NavigationManager 주입
- 구성 요소 만들기 전에 를 추가합니다.
- 아래에 표시된 코드 섹션 추가
@inject NavigationManager navi
@inject CultureService cultureService
<article class="content px-4">
<ChangeCulture/>
@Body
</article>
@code {
// Here we redirect to culture link, for example, from www.example.com to www.example.com/de-DE/
protected override void OnAfterRender(bool firstRender)
{
// Only perform this logic on the first render
if (firstRender)
{
// Extract the relative path from the current URI by removing the base URI
var currentUri = navi.Uri.Replace(navi.BaseUri, ");
// Find the index of the first slash in the relative path
int firstSlashIndex = currentUri.IndexOf('/');
// Prepare the culture-specific URI
string uri;
if (firstSlashIndex >= 0)
{
// Extract the part of the relative path after the first slash
string result = currentUri.Substring(firstSlashIndex + 1);
// Construct the culture-specific URI
uri = "/" + cultureService.Culture + "/" + result;
}
else
{
// If no slash was found in the relative path, navigate to the root path for the current culture
uri = "/" + cultureService.Culture + "/";
}
// Navigate to the determined URI
navi.NavigateTo(uri, false, false);
}
// Call the base OnAfterRender method to ensure proper functioning of the component
base.OnAfterRender(firstRender);
}
}
이제 Blazor의 모든 페이지에 SEO 친화적인 문화 링크를 구현하여 기존 페이지와 향후 페이지에 모두 적용되는 일관된 접근 방식을 확립했습니다. 이 Blazor SEO 튜토리얼을 진행하면서 다음 페이지에 동일한 단계를 적용하여 간소화되고 균일한 프로세스를 보장합니다.
- CultureService 주입
- Culture 매개 변수 생성
- 메소드 OnInitialized에서 배양 매개 변수 설정
- 페이지 태그에 Culture Parameter 추가
다음 코드는 페이지의 변경 사항을 보여줍니다. fetchdata.razor
마지막 단계는 문화 서비스를 탐색 바에 통합하는 것입니다. 이를 통해 항상 현재 문화로 이동할 수 있습니다.
다음 단계로 파일을 수정합니다. NavMenu.razor
- CultureService 주입
- 모든 링크에 현재 문화 추가
Blazor의 SEO 친화적인 문화 링크는 다음과 같은 이유로 중요합니다.
- 검색 가능성 향상: URL에 문화를 포함하면 검색 엔진이 언어별 콘텐츠를 인식하여 검색 순위를 높일 수 있습니다.
- 사용자 경험 향상: 사용자는 URL에서 익숙한 언어 태그를 볼 수 있어 신뢰와 참여도를 높일 수 있습니다.
- URL 일관성 보장: 모든 페이지가 동일한 문화 링크 구조를 유지하여 원활한 탐색 환경을 만듭니다.
- 다국어 콘텐츠 지원: 현재 페이지 컨텍스트를 유지하면서 언어를 쉽게 전환할 수 있습니다.
- 미래 대비: 이 접근 방식을 구현하면 새 페이지가 동일한 패턴을 따르도록 보장하여 확장성을 높일 수 있습니다.
- 글로벌 도달성: 다양한 언어 선호도와 지역을 수용하여 더 많은 청중을 끌어들이십시오.
이제 튜토리얼이 끝났습니다. 향후 페이지를 만들려면 마지막 두 단계를 다시 수행해야 합니다. 코드에 링크를 추가하는 경우 적절한 기능을 보장하기 위해 링크에 문화를 포함해야 합니다.