1

StackOverflowのURLを複製する必要があります。例えばIDとタイトルを含む標準URLを作成するslug

Hidden Features of C#? - (Hidden Features of C#?

または

Hidden Features of C#? - (Hidden Features of C#?

が同じページに行くことができますが、彼らは、ブラウザに戻ったときに最初にウィル常に返されます。

大きなURLが返されるように変更を実装するにはどうすればよいですか?このため

routes.MapRoute(
    null, 
    "questions/{id}/{title}", 
    new { controller = "Questions", action = "Index" }, 
    new { id = @"\d+", title = @"[\w\-]*" }); 

routes.MapRoute(
    null, 
    "questions/{id}", 
    new { controller = "Questions", action = "Index" }, 
    new { id = @"\d+" }); 

に登録

答えて

4

私は前にこれを扱ってきた方法は、2つのルートを持っていることですが、今、コントローラのアクション、

public class QuestionsController 
{ 
    private readonly IQuestionRepository _questionRepo; 

    public QuestionsController(IQuestionRepository questionRepo) 
    { 
     _questionRepo = questionRepo; 
    } 

    public ActionResult Index(int id, string title) 
    { 
     var question = _questionRepo.Get(id); 

     if (string.IsNullOrWhiteSpace(title) || title != question.Title.ToSlug()) 
     { 
      return RedirectToAction("Index", new { id, title = question.Title.ToSlug() }).AsMovedPermanently(); 
     } 

     return View(question); 
    } 
} 

に私たちは恒久的にリダイレクトますidのみを持つ場合はタイトルのスラグ(ハイフンを区切り記号とする小文字のタイトル)を含むURL。渡されたタイトルは、質問タイトルのスラッグバージョンと照合して正しいものにすることで、idと正しいタイトルスラッグの両方を含む質問の標準URLを作成します。

ヘルパーのカップルが

public static class PermanentRedirectionExtensions 
{ 
    public static PermanentRedirectToRouteResult AsMovedPermanently 
     (this RedirectToRouteResult redirection) 
    { 
     return new PermanentRedirectToRouteResult(redirection); 
    } 
} 

public class PermanentRedirectToRouteResult : ActionResult 
{ 
    public RedirectToRouteResult Redirection { get; private set; } 
    public PermanentRedirectToRouteResult(RedirectToRouteResult redirection) 
    { 
     this.Redirection = redirection; 
    } 
    public override void ExecuteResult(ControllerContext context) 
    { 
     // After setting up a normal redirection, switch it to a 301 
     Redirection.ExecuteResult(context); 
     context.HttpContext.Response.StatusCode = 301; 
     context.HttpContext.Response.Status = "301 Moved Permanently"; 
    } 
} 

public static class StringExtensions 
{ 
    private static readonly Encoding Encoding = Encoding.GetEncoding("Cyrillic"); 

    public static string RemoveAccent(this string value) 
    { 
     byte[] bytes = Encoding.GetBytes(value); 
     return Encoding.ASCII.GetString(bytes); 
    } 

    public static string ToSlug(this string value) 
    { 
     if (string.IsNullOrWhiteSpace(value)) 
     { 
      return string.Empty; 
     } 

     var str = value.RemoveAccent().ToLowerInvariant(); 

     str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); 

     str = Regex.Replace(str, @"\s+", " ").Trim(); 

     str = str.Substring(0, str.Length <= 200 ? str.Length : 200).Trim(); 

     str = Regex.Replace(str, @"\s", "-"); 

     str = Regex.Replace(str, @"-+", "-"); 

     return str; 
    } 
} 
を使用しました
関連する問題