Home > Backend Development > C#.Net Tutorial > Tutorial on how to assign values ​​to methods in the .NET MyMVC framework

Tutorial on how to assign values ​​to methods in the .NET MyMVC framework

Y2J
Release: 2017-05-17 11:28:05
Original
1865 people have browsed it

Anyone who has used reflection knows that calling a method is very simple, but how to prepare incoming parameters for a method with [unknown signature]?
Let’s answer this question below. Please look at the implementation process of GetActionCallParameters:

private static object[] GetActionCallParameters(HttpContext context, ActionDescription action)
{    if( action.Parameters == null || action.Parameters.Length == 0 )        return null;    object[] parameters = new object[action.Parameters.Length];    for( int i = 0; i < action.Parameters.Length; i++ ) {        ParameterInfo p = action.Parameters[i];        if( p.IsOut )            continue;        if( p.ParameterType == typeof(NameValueCollection) ) {            if( string.Compare(p.Name, "Form", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.Form;            else if( string.Compare(p.Name, "QueryString", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.QueryString;            else if( string.Compare(p.Name, "Headers", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.Headers;            else if( string.Compare(p.Name, "ServerVariables", StringComparison.OrdinalIgnoreCase) == 0 )
                parameters[i] = context.Request.ServerVariables;
        }        else{            Type paramterType = p.ParameterType.GetRealType();            // 如果参数是简单类型,则直接从HttpRequest中读取并赋值            if( paramterType.IsSimpleType() ) {                object val = ModelHelper.GetValueByKeyAndTypeFrommRequest(
                                                context.Request, p.Name, paramterType, null);                if( val != null )
                    parameters[i] = val;
            }            else {                // 自定义的类型。首先创建实例,然后给所有成员赋值。
                // 注意:这里不支持嵌套类型的自定义类型。                object item = Activator.CreateInstance(paramterType);                ModelHelper.FillModel(context.Request, item, p.Name);
                parameters[i] = item;
            }
        }
    }    return parameters;
}
Copy after login

To understand this code, we need to start from the previous [process of finding Action]. At that stage, you can get The description of an Action is specifically expressed as the ActionDescription type inside the framework:

internal sealed class ActionDescription : BaseDescription{    public ControllerDescription PageController; //为PageAction保留    public MethodInfo MethodInfo { get; private set; }    public ActionAttribute Attr { get; private set; }    public ParameterInfo[] Parameters { get; private set; }    public bool HasReturn { get; private set; }    public ActionDescription(MethodInfo m, ActionAttribute atrr) : base(m)
    {        this.MethodInfo = m;        this.Attr = atrr;        this.Parameters = m.GetParameters();        this.HasReturn = m.ReturnType != ReflectionHelper.VoidType;
    }
}
Copy after login

In the third line of code of the constructor, I can get this method All parameter conditions.
Then, I can loop the definition of each parameter in the GetActionCallParameters method and assign values ​​to them.
This code also explains the reason why only four types of NameValueCollection collections are supported as mentioned earlier.

Note, when I get the type of each parameter, I use the following statement:

Type paramterType = p.ParameterType.GetRealType();
Copy after login

In fact, ParameterType already reflects the type of the parameter, why not use it directly? Woolen cloth?
Answer: Because of [nullable generics]. This type requires special handling.
For example: If a parameter is declared like this: int? id
Then, even if a parameter like id is included in QueryString, I cannot directly convert it to int? To use this type, you must get its [ actual type].
GetRealType() is an extension method, which specifically performs this function:

/// <summary>
/// 得到一个实际的类型(排除Nullable类型的影响)。比如:int? 最后将得到int/// </summary>
/// <param name="type"></param>
/// <returns></returns>public static Type GetRealType(this Type type)
{    if( type.IsGenericType )        return Nullable.GetUnderlyingType(type) ?? type;    else
        return type;
}
Copy after login

If the type of a parameter is a custom type, the framework will first create an instance (calling without parameters constructor), and then assign values ​​to its Property and Field.

Note: Custom types must provide a parameterless constructor.

The code for filling in data members for an instance of a custom type is as follows:

internal static class ModelHelper{    public static readonly bool IsDebugMode;    static ModelHelper()
    {        CompilationSection configSection = 
                    ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;        if( configSection != null )
            IsDebugMode = configSection.Debug;
    }    /// <summary>
    /// 根据HttpRequest填充一个数据实体。    /// 这里不支持嵌套类型的数据实体,且要求各数据成员都是简单的数据类型。    /// </summary>
    /// <param name="request"></param>
    /// <param name="model"></param>    public static void FillModel(HttpRequest request, object model, string paramName)
    {        ModelDescripton descripton = ReflectionHelper.GetModelDescripton(model.GetType());        object val = null;        foreach( DataMember field in descripton.Fields ) {            // 这里的实现方式不支持嵌套类型的数据实体。
            // 如果有这方面的需求,可以将这里改成递归的嵌套调用。            val = GetValueByKeyAndTypeFrommRequest(
                                request, field.Name, field.Type.GetRealType(), paramName);            if( val != null )
                field.SetValue(model, val);
        }
    }    /// <summary>
    /// 读取一个HTTP参数值。这里只读取QueryString以及Form    /// </summary>
    /// <param name="request"></param>
    /// <param name="key"></param>
    /// <returns></returns>    public static string GetHttpValue(HttpRequest request, string key)
    {        string val = request.QueryString[key];        if( val == null )
            val = request.Form[key];        return val;
    }    
    public static object GetValueByKeyAndTypeFrommRequest(                        HttpRequest request, string key, Type type, string paramName)
    {        // 不支持复杂类型        if( type.IsSimpleType() == false )            return null;        string val = GetHttpValue(request, key);        if( val == null ) {            // 再试一次。有可能是多个自定义类型,Form表单元素采用变量名做为前缀。            if( string.IsNullOrEmpty(paramName) == false ) {
                val = GetHttpValue(request, paramName + "." + key);
            }            if( val == null )                return null;
        }        return SafeChangeType(val.Trim(), type);
    }    public static object SafeChangeType(string value, Type conversionType)
    {        if( conversionType == typeof(string) )            return value;        if( value == null || value.Length == 0 )            // 空字符串根本不能做任何转换,所以直接返回null            return null;        try {            // 为了简单,直接调用 .net framework中的方法。
            // 如果转换失败,则会抛出异常。            return Convert.ChangeType(value, conversionType);
        }        catch {            if( IsDebugMode )                throw;            // Debug 模式下抛异常            else
                return null;    // Release模式下忽略异常(防止恶意用户错误输入)        }
    }
}
Copy after login

Before loading data for a custom data type instance, you need to know the instanceObject What are the attributes and fields? The code for this process is as follows:

/// <summary>
/// 返回一个实体类型的描述信息(全部属性及字段)。/// </summary>
/// <param name="type"></param>
/// <returns></returns>public static ModelDescripton GetModelDescripton(Type type)
{    if( type == null )        throw new ArgumentNullException("type");    
    string key = type.FullName;    ModelDescripton mm = (ModelDescripton)s_modelTable[key];    if( mm == null ) {        List<DataMember> list = new List<DataMember>();
        (from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)         select new PropertyMember(p)).ToList().ForEach(x=>list.Add(x));
        (from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public)         select new FieldMember(f)).ToList().ForEach(x => list.Add(x));
        mm = new ModelDescripton { Fields = list.ToArray() };
        s_modelTable[key] = mm;
    }    return mm;
}
Copy after login

After getting all the attributes and field description information of a type, you can use a loop to calculate the data according to the The name of the member goes to QueryString, and the Form reads the required data.

【Related Recommendations】

1. Special Recommendation: "php Programmer Toolbox" V0.1 version download

2. ASP free video tutorial

3. Entry-level .NET MVC example

4. MyMVC frame’s detailed explanation of the process of finding Action

5. .NET MyMVC frame’s detailed explanation of the process of executing Action

6. .NET MyMVC framework tutorial on processing return values

The above is the detailed content of Tutorial on how to assign values ​​to methods in the .NET MyMVC framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template