如何在ASP.NET Core Web API中绑定Json查询字符串 [英] How to bind Json Query string in asp.net core web api

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

问题描述

以下在asp.net网站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核心网站API,我尝试使用following,但没有成功.

[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; }
}

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

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核心使用哪个modelbinder.在我们的情况下很简单,如果模型类型是我们的自定义类型,则使用我们的自定义活页夹.

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服务的位置,并将模型绑定程序插入到列表的前面.这个很重要.如果我们仅将modelbinder添加到列表中,则另一个模型绑定器可能会认为应该改用它(首先使用,先到先得),因此我们可能永远也不会这样做.因此,请务必在开始时将其插入.

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)
{

}

进一步阅读:

  • http://dotnetcoretutorials.com/2016/12/28/custom-model-binders-asp-net-core/
  • https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding

这篇关于如何在ASP.NET Core Web API中绑定Json查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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