1.防止开放重定向:
/// <summary>
/// 防止开放重定向
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static bool IsLocalUrl(string url)
{
if (string.IsNullOrEmpty(url))
return false;
bool result = ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/')); //绝对路径
if (!result && (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)))
{
Uri absoluteUri;
if (Uri.TryCreate(url, UriKind.Absolute, out absoluteUri))
{
return String.Equals(HttpContext.Current.Request.Url.Host, absoluteUri.Host, StringComparison.OrdinalIgnoreCase);
}
}
return result;
//来自Mvc中的UrlHelper.IsLocalUrl,只能判断相对路径
//!string.IsNullOrEmpty(url) && ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/'));
}
2.使用方法:
public void Login(string userName,string password, string returnUrl)
{
//logic code
//validate userName password if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) )
{
return Response.Redirect(returnUrl);
}
return Response.Redirect("/");
}