WebSurfer's Home

トップ > Blog 1   |   ログイン
APMLフィルター

日本語の文字化けの問題(3)

by WebSurfer 2010年6月8日 16:49

Tag cloud の中で日本語の Tag をクリックすると、Tag に関連するポストは正しく表示されるものの、ブラウザのタイトル表示が文字化けします。

例えば、Tag cloud の中の "湘南" をクリックすると、タイトルは All posts tagged '湘南' となるべきところ、All posts tagged 'e6b998e58d97' となってしまいます。

タイトルは、アプリケーションルート直下にある Default.aspx.cs の DisplayTags メソッドの中で、以下のように設定されます。

base.Title = " All posts tagged '" + 
    Request.QueryString["tag"].Substring(1) + "'";

ところが、このクエリ文字列は、UrlEncode してから '%' を除去しているので、上記では UrlDecode されません。(UrlEncode と '%' の除去は、widgets\Tag cloud\widget.ascx.cs の中で Utils.RemoveIllegalCharacters メソッドを使って行っています)

これは DisplayTags メソッドを以下のように直して対応しました。

private void DisplayTags()
{
  if (!string.IsNullOrEmpty(Request.QueryString["tag"]))
  {
    PostList1.ContentBy = ServingContentBy.Tag;
    List<Post> posts = 
      Post.GetPostsByTag(Request.QueryString["tag"].Substring(1));
    PostList1.Posts = 
      posts.ConvertAll(new Converter<Post, IPublishable>(p => p as IPublishable));
    foreach (string t in posts[0].Tags)
    {
      if (Utils.RemoveIllegalCharacters(t).Equals(
         Request.QueryString["tag"].Substring(1),
         StringComparison.OrdinalIgnoreCase))
      {
        base.Title = " All posts tagged '" + t + "'";
        break;
      }
    }
    base.AddMetaTag("description", 
      Server.HtmlEncode(BlogSettings.Instance.Description));
  }
}

ところが、ポスト欄の左下に「Tag: XXXX」というリンクがありますが、この URL のクエリ文字列は UrlEncode がされたのみになっています。('%' は除去されていない。例えば、"湘南" は "%e6%b9%98%e5%8d%97" となります)

これをクリックすると、Tag cloud の中のリンクをクリックしたのと同様に、Default.aspx.cs の DisplayTags メソッドの中で処置されます。そこで、GetPostsByTag メソッドで再度 RemoveIllegalCharacters が引数の文字列に適用され、'%' は除去されるので、正しく Tag に関連する posts が得られますが、foreach の中で一致する t がない(if 文の条件が true にならない)のでタイトルが設定されません。

その結果、ブラウザのタイトルは、All posts tagged 'XXXX' としたいところ、 http://surferonwww.info/BlogEngine... のようになってしまいます。

これは、BlogEngine.Core の中の Web\Controls\PostViewBase.cs の TagLinks メソッドを以下のように直して対応しました。

protected virtual string TagLinks(string separator)
{
  if (Post.Tags.Count == 0)
    return null;

  string[] tags = new string[Post.Tags.Count];
  string link = "<a href=\"{0}/{1}\" rel=\"tag\">{2}</a>";
  string path = Utils.RelativeWebRoot + "?tag=";
  for (int i = 0; i < Post.Tags.Count; i++)
  {
    string tag = Post.Tags[i];
    // 以下で、オリジナルの HttpUtility.UrlEncode(tag) を変更。
    tags[i] = string.Format(CultureInfo.InvariantCulture, 
      link, path, BlogEngine.Core.Utils.RemoveIllegalCharacters(tag), 
      HttpUtility.HtmlEncode(tag));
  }
  return string.Join(separator, tags);
}

クエリ文字列は UrlEncode だけでよさそうな気がしましたが、わざわざ Widget の Tag cloud の方で RemoveIllegalCharacters を使うように変更したのは何か理由がありそうなので、それに合わせることにしました。

Tags: ,

BlogEngine.NET

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。

Calendar

<<  2024年3月  >>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

View posts in large calendar