如何在asp.net core web api中绑定Json Query字符串 [英] How to bind Json Query string in asp.net core web api

查看:31
本文介绍了如何在asp.net core web api中绑定Json Query字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

asp.net web API 中的以下代码运行良好,但在 Asp.net 核心中不起作用.

following code in asp.net web API worked fine but doesn't work in Asp.net core.

端点 api/devices?query={"deviceName":"example"}

[HttpGet]
public Device ([FromUri] string deviceName)
{        
        var device = context.Computers.Where(x => x.deviceName == deviceName);
        return device;
}

[FromUri] 属性不存在 asp.net core web API,我尝试使用以下,但没有成功.

[FromUri] attribute is not present asp.net core web API, and I tried to use following , but no success.

[HttpGet]
public Device  Get([FromQuery] string  deviceName)
{
    return repo.GetDeviceByName(deviceName);
}

推荐答案

不幸的是,没有办法像您那样在 GET 查询中绑定 JSON.您正在寻找的是使用自定义模型绑定器来告诉 ASP.net Core 您想要如何绑定.

Unfortunately there is no way to bind JSON in a GET query like you have there. What you are looking for is to use a custom model binder to tell ASP.net Core how you want to bind.

首先,您要为 JSON 对象构建模型.

First, you want to build your model for your JSON object.

public class MyCustomModel
{
    public string DeviceName { get; set; }
}

接下来您需要构建模型绑定器.下面给出了一个简单的示例,但您显然需要其他检查是否可以转换,Try/Catch 块等.本质上,模型绑定器告诉 ASP.net Core 应该如何绑定模型.您可能还会遇到给定类型的 TypeConverters,如何在模型绑定期间将其更改为另一种类型.现在让我们只使用模型绑定器.

Next you need to build your model binder. A simple example is given below but you would obviously want other checks around if it can be converted, Try/Catch blocks etc. Essentially a model binder tells ASP.net Core how a model should be bound. You might also run into TypeConverters which are given a type, how can I change this to another type during model binding. For now let's just use modelbinders.

public class MyViewModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var jsonString = bindingContext.ActionContext.HttpContext.Request.Query["query"];
        MyCustomModel result = JsonConvert.DeserializeObject<MyCustomModel>(jsonString);

        bindingContext.Result = ModelBindingResult.Success(result);
        return Task.CompletedTask;
    }
}

所以我们所做的就是获取查询字符串并将其反序列化到我们的模型中.

So all we are doing is taking the query string and deserializing it to our model.

接下来我们构建一个提供者.提供程序告诉 ASP.net 核心使用哪个模型绑定器.在我们的例子中很简单,如果模型类型是我们的自定义类型,那么使用我们的自定义绑定器.

Next we build a provider. A provider is what tells ASP.net core which modelbinder to use. In our case it's simple, if the model type is our custom type, then use our custom binder.

public class MyViewModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType == typeof(MyCustomModel))
            return new MyViewModelBinder();

        return null;
    }
}

还有最后一块拼图.在我们的 startup.cs 中,我们找到了添加 MVC 服务的位置,并将我们的模型绑定器插入到列表的前面.这个很重要.如果我们只是将我们的模型绑定器添加到列表中,另一个模型绑定器可能会认为应该使用它(先到先得),因此我们可能永远不会使用它.所以一定要一开始就插入.

And the final piece of the puzzle. In our startup.cs, we find where we add MVC services and we insert our model binder to the front of the list. This is important. If we just add our modelbinder to the list, another model binder might think it should be used instead (First in first served), so we might not ever make it to ours. So be sure to insert it at the start.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(config => config.ModelBinderProviders.Insert(0, new MyViewModelBinderProvider()));
}

现在我们只需创建一个读取数据的操作,不需要任何属性.

Now we just create an action where we read the data, no attributes required.

[HttpGet]
public void Get(MyCustomModel model)
{

}

进一步阅读:

这篇关于如何在asp.net core web api中绑定Json Query字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆