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

how to tell if my asp.net mvc application is accessed via a proxy?

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

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

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

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

[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);
    }
}

(代理确定的候选header key取自this answer