gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:33 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com