Previous: http://www.bkjia.com/kf/201203/122299.html
Why? What are the advantages of other implementation methods?
Many of my friends asked these questions, so I will explain these two questions first. The background processing of Ajax requests is similar to the following, regardless of the use of aspx, asmx, ashx, or IHttpHandler:
// Methods in aspx, asmx, ashx, and IHttpHandler
Public string GetMemberName (int id ){
Return new Member (). GetMemberName (id );
}
Public class Member {
Public string GetMemberName (int id ){
// Do something with id;
Return memberName;
}
}
That is to say, no matter which implementation we use, it is basically a transfer, transfers received requests to the corresponding service class for processing (unless your project does not mind Business Code dispersed in aspx, asmx, ashx, IHttpHandler, and other corners ).
The method proposed in this article is to create an intermediate proxy to transfer requests directly to the business class method. You only need to define the method in the business class, the front-end can be called directly through the specified link without defining An aspx or ashx.
Next we will introduce what we will implement in this article.
Why is Attribute used here?
In the previous article, a friend replied that the received parameters only support data submitted by Form. Can I add QueryString? Of course, this is acceptable, so we have introduced the feature Attribute here to solve the Value Problem of input parameters.
To facilitate future extension, we first define an abstract class ParameterAttribute.
Define ParameterAttribute:
[AttributeUsage (AttributeTargets. Parameter)]
Public abstract class ParameterAttribute: Attribute {
Public object DefaultValue {get; set ;}
Public string Name {get; set ;}
Public ParameterAttribute (){}
Public ParameterAttribute (string name, object defaultValue ){
Name = name;
DefaultValue = defaultValue;
}
Public virtual object GetValue (System. Web. HttpContext context, Type parameterType ){
Object value = GetParameterValue (context )?? DefaultValue;
If (parameterType. FullName = "System. String "){
Return value;
}
If (value. GetType (). FullName = "System. String "){
If (string. IsNullOrEmpty (string) value )){
Value = DefaultValue;
}
}
Return Convert. ChangeType (value, parameterType );
}
Public abstract object GetParameterValue (System. Web. HttpContext context );
}
The ParameterAttribute class inherits from Attribute and limits that this class can only be applied to parameters. At the same time, a DefaultValue Attribute is defined, which is an abstract method GetParameterValue. Some friends may ask why defavalue value does not need to be implemented in a generic way because the class inherited from the Attribute cannot use a generic type.
Next we will define a formattri to process the parameters submitted in Form mode.
Define FormAttribute:
Public class FormAttribute: ParameterAttribute {
Public FormAttribute (){}
Public FormAttribute (string name): base (name, null ){}
Public FormAttribute (string name, object defaultValue): base (name, defaultValue ){}
Public override object GetParameterValue (System. Web. HttpContext context ){
Return context. Request. Form [Name];
}
}
In fact, the definition of this class is very simple. It only returns a value in Request. Form. In this case, it is very easy to implement QueryString. You can change the name to get QueryStringAttribute:
Define QueryStringAttribute:
Public class QueryStringAttribute: ParameterAttribute {
Public QueryStringAttribute (){}
Public QueryStringAttribute (string name): base (name, null ){}
Public QueryStringAttribute (string name, object defaultValue): base (name, defaultValue ){}
Public override object GetParameterValue (System. Web. HttpContext context ){
Return context. Request. QueryString [Name];
}
}
The modified Factory. Execute method:
Void Execute (HttpContext context ){
// Obtain the class for processing the request through reflection based on the request Url
String url = context. Request. Url. AbsolutePath;
String [] array = url. Split (new char [] {'/'}, StringSplitOptions. RemoveEmptyEntries );
String typename = "Biz ";
For (int x = 1; x <array. Length-1; x ++ ){
Typename + = "." + array [x];
}
Type type = this. GetType (). Assembly. GetType (typename, false, true );
If (type! = Null ){
// Obtain the non-parameter constructor of the class
Var constructor = type. GetConstructor (new Type [0]);
// Call the constructor to obtain an instance of the class
Var obj = constructor. Invoke (null );
// Query the Request Method
Var method = type. GetMethod (System. IO. Path. GetFileNameWithoutExtension (url ));
If (method! = Null ){
Var parameters = method. GetParameters ();
Object [] args = null;
If (parameters. Length> 0 ){
Args = new object [parameters. Length];
For (int x = 0; x <parameters. Length; x ++ ){
Var parameterAttr = (Attribute. getcustomattriters (parameters [x], typeof (ParameterAttribute) as ParameterAttribute )?? New FormAttribute ();
ParameterAttr. Name = parameterAttr. Name ?? Parameters [x]. Name;
Args [x] = parameterAttr. GetValue (context, parameters [x]. ParameterType );
}
}
// Execute the method and output the response result
Context. Response. Write (method. Invoke (obj, args ));
}
}
}
There are only two lines more than the code in the previous example. FormAttribute is used by default if ParameterAttribute is not defined.
To facilitate code demonstration, we modified the Javascript code.
The modified front-end Javascript code:
$ (Function (){
// Bind button click event
$ ("# BtnAction"). click (function (){
$. Post ("/Ajax/News/Plus. aspx? Y = "+ $ (" input [name = 'y'] "). val () + "& num3 =" + $ ("input [name = 'Z']"). val (), {x: $ ("input [name = 'X']"). val ()}, function (txt ){
$ ("# Result"). val (txt );
}, "Text ");
});
});
As you can see above, we can take the alias for the demo parameter, and change the parameter z to num3, And the Html code is also slightly modified.
The modified front-end Html code:
<Input type = "text" name = "x" value = "1" class = "txt"/>
<Input type = "button" disabled = "disabled" value = "+" class = "txt btn"/>
<Input type = "text" name = "y" value = "2" class = "txt"/>
<Input type = "button" disabled = "disabled" value = "+" class = "txt btn"/>
<Input type = "text" name = "z" value = "" class = "txt"/>
<Input id = "btnAction" type = "button" value = "=" class = "txt btn"/>
<Input type = "text" readonly = "readonly" id = "result" class = "txt"/>
After running the example, we can see the desired effect. So far, we have solved the problem of supporting parameter values from QueryString, and can also extend the value from other methods, such as Cookie, Session, Application, and even Database, I will not implement it one by one here. If you are interested, may you try it yourself?
Sample project source code:
Click to download
I have prepared articles for several days in the middle of the night, and I have to write sample code. If you are helpful, I suggest you give me some encouragement. Thank you!
To be continued...
From Wolf Robot