首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpRequest.Json集合类HttpRequest.Form

HttpRequest.Json集合类HttpRequest.Form
EN

Code Review用户
提问于 2014-07-10 21:08:56
回答 2查看 3.6K关注 0票数 4

我正在寻找以下代码的正确性和最佳实践审查。我创建了以下代码,以防止使用相同的代码将序列化的JSON转换为在我的HttpHandlers中更容易访问的东西,而不直接将它合并到我的基本处理程序中。当只需要几个值时,我并不总是需要发布完整的实体。

我知道应该避免空的catch语句--我的版本有额外的内容。

代码语言:javascript
复制
/// <summary>
/// Returns a collection of parameters passed via JSON 
/// </summary>
/// <param name="request">HttpRequest</param>
/// <returns>Dictionary<typeparamref name="string"/>,<typeparamref name="object"/> of key, value (string, object) pairs.</returns>
public static Dictionary<string, object> Json(this HttpRequest request)
{
    // Per request caching.
    var jsonCollection = HttpContext.Current.Items["jsonData"] as Dictionary<string, object>;

    if (request.ContentType.StartsWith("application/json") || request.ContentType.StartsWith("text/json"))
    {
        if (jsonCollection == null)
        {
            string jsonData = string.Empty;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                if (!reader.EndOfStream)
                {
                    try
                    {
                        jsonData = reader.ReadToEnd();
                    }
                    catch (OutOfMemoryException ex)
                    {

                    }
                    catch (IOException ex)
                    {

                    }
                    finally
                    {
                        jsonCollection = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
                        HttpContext.Current.Items["jsonData"] = jsonCollection;
                    }

                }
            }
        }
    }
    return jsonCollection;
}

/// <summary>
/// Get Element by index
/// </summary>
/// <param name="request"></param>
/// <param name="index"></param>
/// <returns></returns>
public static object Json(this HttpRequest request, int index)
{
    object obj = null;
    try
    {
        obj = request.Json().ElementAt(index);
    }
    catch (KeyNotFoundException ex)
    {
        obj = null;
    }

    return obj;
}

/// <summary>
/// Get element by key
/// </summary>
/// <param name="request"></param>
/// <param name="key"></param>
/// <returns></returns>
public static object Json(this HttpRequest request, string key)
{
    object obj = null;
    try
    {
        obj = request.Json()[key];
    }
    catch (KeyNotFoundException ex)
    {
        obj = null;
    }

    return obj;
}

07/22/2014快速(阅读:未测试)通用类型化HttpRequest.Json

代码语言:javascript
复制
public static T GetValue<T>(this IDictionary collection, string key)
{
    if (collection == null)
    {
        return default(T);
    }

    var value = collection[key];

    if (value == null)
    {
        return default(T);
    }

    var type = typeof(T);

    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        type = Nullable.GetUnderlyingType(type);
    }

    var converter = TypeDescriptor.GetConverter(type);

    if (!converter.CanConvertTo(value.GetType()))
    {
        return default(T);
    }

    return (T)converter.ConvertTo(value, type);
}


public static T Json<T>(this HttpRequest request)
{
    // Per request caching -- See GetValue<T> above.
    T jsonCollection = HttpContext.Current.Items.GetValue<T>("jsonData");

    if (request.ContentType.StartsWith("application/json") || request.ContentType.StartsWith("text/json"))
    {
        if (jsonCollection == null)
        {
            string jsonData = string.Empty;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                if (!reader.EndOfStream)
                {
                    try
                    {
                        jsonData = reader.ReadToEnd();
                    }
                    catch (OutOfMemoryException ex)
                    {

                    }
                    catch (IOException ex)
                    {

                    }
                    finally
                    {
                        jsonCollection = JsonConvert.DeserializeObject<T>(jsonData);
                        HttpContext.Current.Items["jsonData"] = jsonCollection;
                    }

                }
            }
        }
    }
    return jsonCollection;
}
EN

回答 2

Code Review用户

发布于 2014-07-10 23:37:14

我将把肉留给其他人,但是这里有一些对索引方法的快速改进。

尝试-捕获是缓慢的,如果可能的话要避免.我就是这样做的。

代码语言:javascript
复制
/// <summary>
/// Get Element by index
/// </summary>
/// <param name="request">HttpRequest</param>
/// <param name="index"></param>
/// <returns></returns>
public static object Json(this HttpRequest request, int index)
{
    var json = request.Json();
    if (json.Count() < index + 1)
    {
        return null;
    }

    return json.ElementAt(index);
}


/// <summary>
/// Get element by key
/// </summary>
/// <param name="request">HttpRequest</param>
/// <param name="key"></param>
/// <returns></returns>
public static object Json(this HttpRequest request, string key)
{
    object obj = null;
    request.Json().TryGetValue(key, out obj);
    return obj;
}
票数 1
EN

Code Review用户

发布于 2014-07-22 00:00:31

实现是好的,但在我看来,设计是值得怀疑的。任何时候,当您返回一个像Dictionary<String, Object>这样的错误类型的包时,您应该考虑一下您封装得有多好。处理程序对象是唯一知道它所期望的参数类型的对象,对吗?因此,它应该将参数反序列化为一些业务对象,比如Employee[],而不是包含一系列字典的字典。

由于您没有提供任何用例,所以很难说您应该拥有什么样的接口。反序列化函数可能是泛型的,每个子类都可以指定它生成的类型。

票数 0
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/56693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档