eightHundreds
11/24/2017 - 4:59 AM

跳转的正确姿势

注意header中不能有中文

[HttpGet("mobile/{*urlParams}")]
[HttpGet("msg/{*urlParams}")]
public IActionResult RedirecToNewUrl(string urlParams)
{
    var encodedStrBuilder=new StringBuilder();
    foreach (var fragment in urlParams.Split('/'))
    {
        encodedStrBuilder.AppendFormat("{0}/", TryUrlEncode(fragment));
    }
    encodedStrBuilder.Remove(encodedStrBuilder.Length - 1, 1);
    
    return RedirectPermanent($"{Request.Scheme}://{Request.Host}/{encodedStrBuilder}{Request.QueryString}");
}

private string TryUrlEncode(string mayUndecodedStr)
{
    if (WebUtility.UrlDecode(mayUndecodedStr) == mayUndecodedStr)
    {
        return WebUtility.UrlEncode(mayUndecodedStr);
    }
    return mayUndecodedStr;
}