如何判断我的asp.net mvc应用程序是否通过代理访问?

时间:2015-02-05 11:40:18

标签: c# asp.net-mvc http proxy httpwebrequest

我想根据用户是否使用代理服务器来提供其他内容。

        if(FROM_PROXY){
          routes.MapRoute(
            name: "ProxyDefault",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "HomeProxy",
              action = "Index", id = UrlParameter.Optional 
            }
          );
        }

所以, 如何检测我的asp.net mvc应用程序是否通过代理访问?

1 个答案:

答案 0 :(得分:0)

您可以注册以下全局过滤器:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class BlockProxyAccessAttribute : ActionFilterAttribute
{
    private static readonly string[] HEADER_KEYS = { "VIA", "FORWARDED", "X-FORWARDED-FOR", "CLIENT-IP" };
    private const string PROXY_REDIR_URL = "/error/proxy";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var isProxy = filterContext.HttpContext.Request.Headers.AllKeys.Any(x => HEADER_KEYS.Contains(x));

        if (isProxy)
            filterContext.Result = new RedirectResult(PROXY_REDIR_URL);
    }
}

(代理确定的候选标题密钥取自this answer