如何在mvc4加密查询字符串ID的ActionLink [英] How to encrypt the query string ID in mvc4 ActionLink

查看:233
本文介绍了如何在mvc4加密查询字符串ID的ActionLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我如何可以传递 ActionLink的加密ID,这是我写在我的视图

  @model IEnumerable的< forumAPP.tblTechnology>
@foreach(以型号VAR项)
{
字符串techName = item.TechName;
@ Html.ActionLink(techName,详细信息,家,新的{TopicID = item.TechID},NULL)//这里我想给TopicID加密
< BR />
< BR />
@ Html.DisplayFor(modelItem => item.TechDesc)
}


解决方案

下面是几个简单的方法,您可以使用EN code /德code。
带连接codeD值不是安全,因为你可以看到,它的解码是微不足道的。如果你的目标是要混淆的ID,这将工作。如果你需要的安全的话,你应该采取不同的方法。

 公共字符串连接code(字符串连接codeME)
{
    字节[] EN codeD = System.Text.Encoding.UTF8.GetBytes(EN codeME);
    返回Convert.ToBase64String(EN codeD);
}公共静态字符串德code(字符串德codeME)
{
    字节[] EN codeD = Convert.FromBase64String(德codeME);
    返回System.Text.Encoding.UTF8.GetString(EN codeD);
}

所以,你可以放在你的控制器,这些方法和EN codeD TechId通过与viewBag视图

  INT techId = 1;
变种EN codeD = EN code(id.ToString());
ViewBag.En codeD = EN codeD;

然后用它在你的链接

  @ Html.ActionLink(techName,详细信息,家,新的{TopicID = ViewBag.En $ C $} CD,NULL)

(虽然,你真的应该考虑使用视图模型。ViewBag,而convienent,轻松地将数据传递到视图,不被认为是最好的做法。成为舒适的视图模型和强类型的意见会让你MVC生活在未来要容易得多。更何况,生产出更清洁,更容易维护code对于那些跟随你。)

Hi all how can I pass the encrypted id in ActionLink, this is what I written in my view

@model IEnumerable<forumAPP.tblTechnology>
@foreach (var item in Model)
{
string techName=item.TechName;
@Html.ActionLink(techName, "Details","Home", new { TopicID = item.TechID },null) // Here I would like to encrypt the TopicID
<br />
<br />
@Html.DisplayFor(modelItem => item.TechDesc)
}

解决方案

Here are a couple of simple methods you can use to encode/decode. The encoded value is not secure, and as you can see, decoding it is trivial. If your goal is to obfuscate the id, this will work. If you need to secure it, you should take a different approach.

public string Encode( string encodeMe )
{
    byte[] encoded = System.Text.Encoding.UTF8.GetBytes( encodeMe );
    return Convert.ToBase64String( encoded );
}

public static string Decode( string decodeMe )
{
    byte[] encoded = Convert.FromBase64String( decodeMe );
    return System.Text.Encoding.UTF8.GetString( encoded );
}

So you could place these methods in your controller, and pass the encoded TechId to the view with viewBag

int techId = 1;
var encoded = Encode(id.ToString());
ViewBag.Encoded = encoded;

And then to use it in your link

@Html.ActionLink(techName, "Details","Home", new { TopicID = ViewBag.Encoded },null)

(Though, you should really consider using a view model. ViewBag, while a convienent and easy way to pass data to the view, is not considered to be best practice. Becoming comfortable with view models and strongly typed views will make your mvc life much easier in the future. Not to mention, produce cleaner and more maintainable code for those that follow you.)

这篇关于如何在mvc4加密查询字符串ID的ActionLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆