javascript - 如何从javascript json接收WebAPI中的字典

标签 javascript c# .net json asp.net-web-api

我在 WebAPI 中有这个 Controller 函数:

public class EntityController : APIController
{
       [Route("Get")]
       public HttpResponseMessage Get([FromUri]Dictionary<string, string> dic)
       { ... }
}

我的请求在 javascript 中看起来像这样:

{
     "key1": "val1",
     "key2": "val2",
     "key3": "val3"
},

但解析失败。有没有办法在不编写太多代码的情况下完成这项工作?谢谢

我的完整要求:

http://localhost/Exc/Get?dic={"key1":"val1"}

最佳答案

您可以使用自定义模型 Binder :

public class DicModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(Dictionary<string, string>))
        {
            return false;
        }

        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val == null)
        {
            return false;
        }

        string key = val.RawValue as string;
        if (key == null)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
            return false;
        }

        string errorMessage;

        try
        {
            var jsonObj = JObject.Parse(key);
            bindingContext.Model = jsonObj.ToObject<Dictionary<string, string>>();
            return true;
        }
        catch (JsonException e)
        {
            errorMessage = e.Message;
        }

        bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value: " + errorMessage);
        return false;
    }
}

然后使用它:

public class EntityController : APIController
{
    [Route("Get")]
    public HttpResponseMessage Get([ModelBinder(typeof(DicModelBinder))]Dictionary<string, string> dic)
    { ... }
}

在 ModelBinder 中,我使用 Newtonsoft.Json 库解析输入字符串,然后将其转换为字典。您可以实现不同的解析逻辑。

关于javascript - 如何从javascript json接收WebAPI中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43937115/

相关文章:

javascript - 找不到模块 : Can't resolve 'styled-component'

C# 构造函数重载 + 显式强制转换 = 缺少 .dll 引用

c# - 如何先使用 DotConnect For PostgreSQL 和 Entity Framework 代码

javascript - 基于翻译字符串的加载指令

javascript - 如何在 javascript 中使用功能链接和组合?

javascript - 使用ajax接收php中序列化的数据

c# - 在 C# 代码中使用下标字符?

c# - Unity Raycast() 和 DrawRay() 使用相同的输入创建不同的光线

c# - 如何获取具有给定属性的属性列表?

.net - 对缩小 PDF 文件有什么建议吗?