Using MVC filter to implement URL parameter encryption and decryption

Source: Internet
Author: User
Tags decrypt httpcontext to domain

Recently in an iOS app to do interface docking, has not encountered any big problem, but one day found that through the software to parse the URL of the app, and then directly through the URL stitching to modify the interface data, this look make the data security and accuracy are reduced, so the thought of the URL encryption.

And then on the Internet to check the URL of the encryption algorithm, the use of more common or Base64 encryption, but for how to implement encryption, online information is not much, it may be my search for the wrong keyword. Since there is no ready-made reference document, then you can only rely on their own. Because all controllers inherit a base controller, it is quite natural to think of doing something in the base controller, because the parameters in the URL need to be decrypted before the specific action is executed. So Lenovo to the IHttpModule interface used to do the ASP, but MVC has a better function, that is, the filter Filter,mvc a total of four default filter interfaces, Iauthorizationfilter, Iactionfilter, Iresultfilter and Iexceptionfilter, about the execution time and usage of these four kinds of filter There are many on the network, here do not repeat. The following on my groping process to do a description, but also for your reference, if you have a better way, but also hope to inform.

To be able to decrypt a URL's parameters, you first need to get the arguments passed by the HttpRequest. First create a filter, I'm named Decodeurlfitler, inherit to ActionFilterAttribute, this class has inherited the Iactionfilter interface, it has four abstract methods, are onactionexecuted (executed after action is executed), onactionexecuting (executed before action executes), onresultexecuted (executed after the view view is rendered), Onresultexecuting (executed before the view view is rendered). Obviously, we need to rewrite the OnActionExecuting method to decrypt the parameters in the URL before the action executes.

First step: Get query parameters in the URL

After getting the query parameters, if you look closely, you will find that the parameters of the Base64 format are sometimes urencode, so in order to be able to accurately decode the Base64 later, we need to urldecode processing the parameters.

public class appactionfilter:actionfilterattribute{public override void OnActionExecuting (ActionExecutingContext fil    Tercontext) {Httprequestbase bases = (httprequestbase) filterContext.HttpContext.Request; String url = bases. Rawurl.tostring (). ToLower ();
Gets the parameter in the URL string queryString = bases. Querystring.tostring ();
UrlDecode Processing of acquired parameters
queryString = Httputility.urldecode (queryString);
}}

Get parameters and processing in the blog park now there are a lot of articles are introduced, in MSDN to look at the type of method, the above code can be easily written out, the more difficult is how to replace the parsed URL parameters of the previous parameters, and then jump to the corresponding action, and then return the results of the execution to the client. I have been groping on this issue for a long time, finally found a better way, the following is to say I touched a few pieces of stone.

Step two: URL jumps

First stone: Using Redirectresult

The first thought is to re-spell the URL, the parsed parameters into a full URL, get the path of the URL can use the Httprequestbase filepath property to get to the path, and then get to domain, In addition to the decryption of the querystring can be stitched into a complete URL. But if you look at the browser's message, you will find that this is actually a URL redirection, if so, we have not implemented the purpose of URL encryption, URL redirection, will be decrypted URL to the client, which let our URL exposed, which is completely contrary to our idea, decisively give up.

Second Stone: Using IHttpHandler

Later, when checking the information, it was mentioned that using IHttpHandler's ProcessRequest to handle the Web request.

FilterContext.RequestContext.HttpContext.RewritePath (URL);//url is the virtual path IHttpHandler HttpHandler = new Mvchttphandler ( ); Httphandler.processrequest (System.Web.HttpContext.Current);

This can also be done, but if your action parameter has a non-string type, you will get an error when executing this method, although you can't see it, but you're in Global.asax.cs's application_. Use Server.GetLastError () in the error method. GetBaseException (); Catch exceptions, you'll find parameters like the int type required by the XXXXXX method, but pass through the string type and so on. Although the function is realized, but it is uncomfortable to look at, so continue to explore the next program.

Third Stone: Use Actionparameters to modify context parameters

Write code is to be patient, after my long groping, I found that there is no encrypted URL, ActionExecutingContext actionparameters property is the URL of the query parameter collection, is a dictionary<string, The type of object>, but if the URL is encrypted, the Actionparameters parameter collection has only key, no value, so I think, can you change the value inside the actionparameters, Then, in the OnActionExecuting method with calling its parent class ActionFilterAttribute, say no more, post the implemented code.

Gets the description of the Access action parameter, primarily the type of the parameter and the parameter name parameterdescriptor[] PDS = FilterContext.ActionDescriptor.GetParameters (); 2 3//Refill parameter 4 string paramname = ""; 5 String paramvalue = ""; 6 foreach (string param in Parameters) 7 {8 paramname = P Aram. Split (' = ') [0]; 9 paramvalue = Httputility.urldecode (param.                             Split (' = ') [1]); (parameterdescriptor PD in PDS) 11 {12 if (paramname = = PD.                                 ParameterName) 13 {14//Determine the type of the parameter, if it is the shape of the data, then convert the parameters into shaping data 15 if (PD. ParameterType.Name.ToLower () = = "Int32" | | Pd. ParameterType.Name.ToLower () = = "Nullable ' 1") LTERCONTEXT.ACTIONPARAMETERS.ADD (ParamName,Convert.ToInt32 (Paramvalue));}19 Else20                                 {FILTERCONTEXT.ACTIONPARAMETERS.ADD (paramname, paramvalue); 22                         }23 break;24}25 }26}28}29 Base. OnActionExecuting (Filtercontext);

But here to share with you, the use of parameter replacement process encountered problems and noteworthy points.

1, before adding parameters, it is necessary to use the clear () method to clear the default generated parameters, or re-add the parameters, the "Dictionary already exists the value of this key"; Another way is to iterate over the arguments passed and the parameters in the Actionparameters, The value of the replacement parameter.

2. The 2nd note is the type of the parameter, the type and name of the parameter can be obtained through the Actiondestriptor method, if the parameter type passed is inconsistent with the parameter type defined by the action, an exception with inconsistent argument type is thrown.

3, the last note of the nullable type of parameters, if the action parameter is full of nullable types of non-nullable type parameters, when the nullable parameter has a value, then all the remaining parameters are passed, and assigned a value. The simplest way is to iterate over the parameters of the Actiondestriptor, add all the parameters to the actionparameters and enclose the values.

//If a nullable parameter is filled, then a parameter cannot be added to the parameter list that is not nullable and is not in the request parameter list, or it will be error 31 (parameterdescriptor PD in PDS) {!filtercontext.actionparameters.keys.contains (PD. parametername)). {if (PD). ParameterType.Name.ToLower () = = "Nullable ' 1") {Filtercont Ext. Actionparameters.add (PD. ParameterName, NULL), PNS}38 else if (PD. DefaultValue = = null) FILTERCONTEXT.ACTIONPARAMETERS.ADD (PD.                                 ParameterName, "");}42 else43 {44 FILTERCONTEXT.ACTIONPARAMETERS.ADD (PD. ParameterName, PD. DefaultValue)}46}47} 

Another way is to build the routing table, but I have not tried, interested can try.

If you have better methods and suggestions, welcome more stickers to make bricks.

Using MVC filter to implement URL parameter encryption and decryption

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.