【问题标题】:How to Retrieve Data with Hashtable as a condition in WebAPI?如何使用 Hashtable 作为 WebAPI 中的条件检索数据?
【发布时间】:2018-03-11 04:32:33
【问题描述】:

我知道如何在 webapi 中使用一个字符串进行检索。但我不知道如何在我的 webapi 中使用哈希表。因为在哈希表中,我对每种形式都有不同的条件,但调用相同的 api。

我正在使用 .net3.5

例子:

System.Collections.Hashtable _condition = new System.Collections.Hashtable();
            if (TPX.StringHelper.NVL(cbxStatus.EditValue, "-Please Select-") != "-Please Select-")
                _condition.Add("Status", cbxStatus.EditValue.ToString());
            if (TPX.StringHelper.NVL(cbxCenter.EditValue, "-Please Select-") != "-Please Select-")            
                _condition.Add("Center", cbxCenter.EditValue.ToString());
            if (chkHideDone.Checked)
                _condition.Add("IsDone", Convert.ToInt32(!chkHideDone.Checked));

        _condition.Add("StartDate", dtpBegin.DateTime.ToString("yyyyMMdd"));
        _condition.Add("EndDate", dtpEnd.DateTime.ToString("yyyyMMdd"));

        string itemJson = Newtonsoft.Json.JsonConvert.SerializeObject(_condition);

        string navURL = GlobalParameters.Host + "api/Order/RetrieveOrderList?conditions="+itemJson;

        using (System.Net.WebClient webClient = new System.Net.WebClient())
        {
            webClient.Headers["Content-Type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;                

            string sJson = webClient.DownloadString(navURL);  List<Models.OrderList> myDeserializedObjList = (List<Models.OrderList>)Newtonsoft.Json.JsonConvert.DeserializeObject(sJson, typeof(List<Models.OrderList>));
            grdOrder.DataSource = myDeserializedObjList;
        }

下载字符串时出错 (webclient.downloadstring(navURL))。 注意:我已经复制了相同的逻辑来再创建一个并由一个字段而不是哈希表过滤我没有问题。 我真的需要 hashtbale,因为我在项目的不同地方使用相同的逻辑,只是提供的条件不同。

我非常感谢您提供任何有价值的意见。谢谢。

【问题讨论】:

    标签: c# json asp.net-web-api hashtable


    【解决方案1】:

    当您将Hashtbale 序列化为 JSON 时,生成的字符串包含引号(可能还有其他特殊字符),它们在 URL querystring 中不是有效字符。这些字符必须使用percent encoding 进行编码。为此,您可以使用Uri.EscapeDataString 静态方法。

    string navURL = GlobalParameters.Host + "api/Order/RetrieveOrderList?conditions=" + Uri.EscapeDataString(itemJson);
    


    编辑:
    您可能会在中找到一些如何将 Dictionary 传递给 WebAPI 的示例

    但这对我有用:

    // Declare binder that will convert parameters to Hashtable
    public class HashtableBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var json = bindingContext?.ValueProvider?.GetValue(bindingContext.ModelName)?.AttemptedValue as string;
            if (json != null)
            {
                //Deserialize using Microsoft's JSON serializer
                var serializer = new JavaScriptSerializer();
                bindingContext.Model = serializer.Deserialize<Hashtable>(json);
                //or deserialize using Newtonsoft JSON convertor
                //bindingContext.Model = JsonConvert.DeserializeObject<Hashtable>(json);
                return true;
            }
            return false;
        }
    }
    
    
    // In your controller, decorate parameter
    // with FromUri attribute and specify HashtableBinder
    // as BinderType
    [HttpGet]
    [Route("api/Order/RetrieveOrderList")]
    public void RetrieveOrderList([FromUri(BinderType = typeof(HashtableBinder), Name = "conditions")]Hashtable conditions)
    {
        // access hashtable in conditions parameter, e.g. var status = conditions["Status"]
    }
    

    【讨论】:

    • 我按照你的建议试过了。但仍然返回相同的错误(错误 500,内部服务器错误)。在应用更改之前,我的 api 链接是这样的 localhost:8989/api/Order/RetrieveOrderList?conditions={"StartDate":"20170923","Status":"100","EndDate":"20170930"} 现在是 localhost:8989/api/Order/…
    • 虽然没有更多细节不能100%确定,但错误500通常发生在服务器上处理WebAPI请求的方法抛出未处理的异常时。所以问题现在不在 WebClient 上,而是在服务器上。你应该调试你的服务器代码,看看为什么会抛出异常。
    • @Nuf,我使用相同的逻辑并且我的数据模型在其他项目中没有任何异常。当我调用 throw webapi 时,它给出了错误。所以我觉得我的api调用方法有问题。我正在使用 HTTPGET。我不确定 HTTP Post 是否可以用于检索数据。我也试过了。如果在 webapi 中使用哈希表条件检索一些示例将会很棒。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多