c# - 加密 URL 中的路由数据

标签 c# asp.net asp.net-mvc encryption

在我的 ASP.NET MVC 应用程序中,我想加密路由数据而不是 QueryString,换句话说:

我正在使用 ASP.NET MVC 默认路由模式:

   routes.MapRoute(
             name: "Default",
            url: "{controller}/{action}/{id}",
             defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
             namespaces: new[] { "WHATEVER" }
         ); 

我的操作方法采用 id 参数:

  public ActionResult Example(int id)
  {
    return View();
  }

现在将数据传递给此操作方法的我的网址是:

/ Controller /示例/5

我想要这样

/Controller/Example/ENCRYPTEDPARAMTER

提前致谢

最佳答案

我找到了nice guide做我想做的事,但使用查询字符串但不是路由数据,所以我更新了它以使用查询字符串和路由数据,该指南基于创建自定义帮助程序和自定义属性,因此可以轻松进行更改,我将通过代码提及我的更改:

自定义助手

  public static MvcHtmlString EncodedActionLink(this HtmlHelper htmlHelper, string linkText, string Action, string ControllerName, string Area, object routeValues, object htmlAttributes)
    {
        string queryString = string.Empty;
        string htmlAttributesString = string.Empty;
       //My Changes
        bool IsRoute = false;
        if (routeValues != null)
        {
            RouteValueDictionary d = new RouteValueDictionary(routeValues);
            for (int i = 0; i < d.Keys.Count; i++)
            {
                 //My Changes
                if (!d.Keys.Contains("IsRoute"))
                {
                    if (i > 0)
                    {
                        queryString += "?";
                    }
                    queryString += d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
                }
                else
                {
                    //My Changes
                    if (!d.Keys.ElementAt(i).Contains("IsRoute"))
                    {
                        queryString += d.Values.ElementAt(i);
                        IsRoute = true;
                    }
                }
            }
        }

        if (htmlAttributes != null)
        {
            RouteValueDictionary d = new RouteValueDictionary(htmlAttributes);
            for (int i = 0; i < d.Keys.Count; i++)
            {
                htmlAttributesString += " " + d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
            }
        }


        StringBuilder ancor = new StringBuilder();
        ancor.Append("<a ");
        if (htmlAttributesString != string.Empty)
        {
            ancor.Append(htmlAttributesString);
        }
        ancor.Append(" href='");
        if (Area != string.Empty)
        {
            ancor.Append("/" + Area);
        }

        if (ControllerName != string.Empty)
        {
            ancor.Append("/" + ControllerName);
        }

        if (Action != "Index")
        {
            ancor.Append("/" + Action);
        }
        //My Changes
        if (queryString != string.Empty)
        {
            if (IsRoute == false)
                ancor.Append("?q=" + Encrypt(queryString));
            else
                ancor.Append("/" + Encrypt(queryString));
        }
        ancor.Append("'");
        ancor.Append(">");
        ancor.Append(linkText);
        ancor.Append("</a>");
        return new MvcHtmlString(ancor.ToString());
    }

自定义属性:

  public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        int Id;

        Dictionary<string, object> decryptedParameters = new Dictionary<string, object>();
        if (HttpContext.Current.Request.QueryString.Get("q") != null)
        {
            string encryptedQueryString = HttpContext.Current.Request.QueryString.Get("q");
            //string decrptedString = Decrypt(encryptedQueryString.ToString());
            string decrptedString = Decrypt(encryptedQueryString.ToString());
            string[] paramsArrs = decrptedString.Split('?');

            for (int i = 0; i < paramsArrs.Length; i++)
            {
                string[] paramArr = paramsArrs[i].Split('=');
                decryptedParameters.Add(paramArr[0], Convert.ToInt32(paramArr[1]));
            }
        }
        else if (!HttpContext.Current.Request.Url.ToString().Contains("?"))
        {
            //if (int.TryParse(Decrypt(HttpContext.Current.Request.Url.ToString().Split('/').Last()), out Id))
            if (int.TryParse(Decrypt(HttpContext.Current.Request.Url.ToString().Split('/').Last()), out Id))
            {
                string id = Id.ToString();
                decryptedParameters.Add("id", id);
            }
        }
        else if (HttpContext.Current.Request.Url.ToString().Contains("?"))
        {
            //if (int.TryParse(Decrypt(HttpContext.Current.Request.Url.ToString().Split('/').Last().Split('?')[0]), out Id))
            if (int.TryParse(Decrypt(HttpContext.Current.Request.Url.ToString().Split('/').Last().Split('?')[0]), out Id))
            {
                string id = Id.ToString();
                if (id.Contains('?'))
                {
                    id = id.Split('?')[0];
                }
                decryptedParameters.Add("id", id);
            }

            string[] paramsArrs = HttpContext.Current.Request.Url.ToString().Split('/').Last().Split('?');
            for (int i = 1; i < paramsArrs.Length; i++)
            {
                string[] paramArr = paramsArrs[i].Split('=');
                decryptedParameters.Add(paramArr[0], Convert.ToInt32(paramArr[1]));
            }
        }

        for (int i = 0; i < decryptedParameters.Count; i++)
        {
            filterContext.ActionParameters[decryptedParameters.Keys.ElementAt(i)] = decryptedParameters.Values.ElementAt(i);
        }
        base.OnActionExecuting(filterContext);

    }

其实我的改动并没有那么大,所以本文的出处实际上是guide .

关于c# - 加密 URL 中的路由数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27885975/

相关文章:

javascript - 当我使用 angularjs 从 MVC Controller 获取数据时,OwlCarousel 不工作

c# - 在 html 电子邮件中发送 DataTable 的内容,从 DataTable 生成 HTML 的首选方法是什么?

c# - asp.net session 变量超时时出现 500 错误

javascript - 如何使用 jquery 或 javascript 单击按钮时向右滑动 div?

asp.net-mvc - 如何从我自己的 HtmlHelper 中访问 HtmlHelper 方法?

asp.net-mvc - ASP.NET MVC4, View 将旧值返回给 Controller

c# - HTML解析器

c# - 模态 iframe 中的 PDF 在 IE 中呈现为空白

c# - 如何在 C# 互操作调用中从 C# 实例化数组中的 C 取回数据?

asp.net - FormsAuthentication 类相对于 session 变量的优势