如何在ASP.NET Core Web API中绑定Json查询字符串

编程入门 行业动态 更新时间:2024-10-21 07:48:18
本文介绍了如何在ASP.NET Core Web API中绑定Json查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下在asp网站API中的代码工作正常,但在Asp核心中不起作用.

following code in asp web API worked fine but doesn't work in Asp 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核心网站API,我尝试使用following,但没有成功.

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

Next we build a provider. A provider is what tells ASP 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) { }

进一步阅读:

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

更多推荐

如何在ASP.NET Core Web API中绑定Json查询字符串

本文发布于:2023-11-14 19:36:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   绑定   如何在   NET   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!