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

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

问题描述

如何在ActionLink中传递加密的ID.这就是我在view中写的内容:

How can I pass the encrypted id in ActionLink. This is what I have 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)
}

推荐答案

以下是几个可用于编码/解码的简单方法. 编码后的值并不安全,如您所见,对其进行解码是微不足道的.如果您的目标是混淆ID,则可以使用.如果需要安全,则应采用其他方法.

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

因此您可以将这些方法放置在控制器中,然后使用viewBag将编码的TechId传递给视图

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;

然后在链接中使用它

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

(尽管,您应该真正考虑使用视图模型.ViewBag虽然是将数据传递到视图的便捷简便方法,但不被认为是最佳实践.熟悉视图模型和强类型视图将使您的将来,mvc的生活将变得更加轻松.更不用说,为跟随您的用户提供更简洁,更可维护的代码.

(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.)

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

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