ASP.NET Core MVC-模型绑定:使用属性[FromBody](BodyModelBinder)绑定接口模型 [英] ASP.NET Core MVC - Model Binding : Bind an interface model using the attribute [FromBody] (BodyModelBinder)

查看:953
本文介绍了ASP.NET Core MVC-模型绑定:使用属性[FromBody](BodyModelBinder)绑定接口模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的操作方法的接口模型与内容类型为application/json的请求绑定在一起.我在操作方法中使用了[FromBody]属性.

I want to bind an interface model from my action method with a request that the content-type is application/json. I'm using the [FromBody] attribute in my action method.

我尝试通过以下链接创建从ComplexTypeModelBinder派生的自定义modelBinder:

I tried to create a custom modelBinder derived from ComplexTypeModelBinder, by following this link: Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces, but it doesn't work, my model is always null. I learned after that when you use the atribute [FromBody] the BodyModelBinder is called and internally is calling JsonInputFormatter and it doesn't use the custom modelBinder.

我正在寻找一种绑定我的接口模型的方法.我可以使用MVC DI来映射每个接口及其实现.我的动作方法定义为:

I'm looking for a way to bind my interface model. I can use the MVC DI to map each interface with its implementation. My action method is defined as :

public async Task<IActionResult> Create(IOperator user)
    {
        if (user == null)
        {
            return this.BadRequest("The user can't not be null");
        }

        if (!this.ModelState.IsValid)
        {
            return this.BadRequest(this.ModelState);
        }

            IOperator op = await this.AuthenticationFrontService.CreateOperatorAsync(user.Login, user.Password, user.FirstName, user.LastName, user.ValidUntil, user.Role, user.Comment);
        return new CreatedAtActionResult("Get", "operators", new { id = ((Operator)op).Id }, op);
    }

我通过在界面中使用MetadataType属性尝试了另一种解决方案,但是它在名称空间System.ComponentModel.DataAnnotations中不存在,并且我读到asp.net core mvc不使用此属性

I tried another solution by using the MetadataType attribute in my interface but it doesn't exist in the namespace System.ComponentModel.DataAnnotations and i read that asp.net core mvc doesn't use this attribute Asp.Net MVC MetaDataType Attribute not working. I don't want to install the package microsoft.aspnetcore.mvc.dataannotations in domain model project to use the ModelDataType attribute.

我尝试了另一种解决方案,方法是创建一个自定义的JsonInputFormater,换句话说,我派生了JsonInputFormatter类并通过分析源代码,我发现JsonSerializer无法反序列化逻辑接口.因此,我正在寻找一种可以通过使用解析器或通用转换器来自定义jsonserializer的解决方案.

I tried another solution by creating a custom JsonInputFormater in other words i derived the class JsonInputFormatter and by analyzing the source code, i've found that the JsonSerializer couldn't deserialize an interface which is logical. So i'm looking for a solution where i could custom the jsonserializer maybe by using a resolver or a generic converter.

任何帮助将不胜感激.

谢谢.

推荐答案

使用接口对C#方法很好,但是MVC需要知道在调用Action时应实例化哪种具体类型,因为它正在创建.它不知道使用哪种类型,因此它无法将来自Form/QueryString/etc的输入绑定到.创建一个非常基本的模型以供您在操作中使用,如果您的目标是保持接口IOperator不变,那么它什么也不做,而是实现您的接口IOperator,并将其设置为您的Action参数,并且应该可以正常工作.

Using an interface is fine for a C# method, but MVC needs to know what concrete type it should instantiate when calling an Action since it's creating it. It doesn't know what type to use, so it can't bind input from Form/QueryString/etc to. Create a very basic model for use in your action that does nothing but implement your interface IOperator, if your goal was to keep it slim, and set that to your Action parameter and it should work fine.

我也尝试过在动作上使用接口,并且通过我自己的搜索,除了使用类而不是接口进行绑定之外,我发现没有其他方法可以使它起作用.

I have tried using an interface on a action as well, and through my own searching, I found no way to get it to work, other than just using classes instead of interfaces to bind to.

public class Operator : IOperator
{
    //Implement interface
}

.

public async Task<IActionResult> Create(Operator user)
{
    if (user == null)
    {
        return this.BadRequest("The user can't not be null");
    }

    if (!this.ModelState.IsValid)
    {
        return this.BadRequest(this.ModelState);
    }

        IOperator op = await this.AuthenticationFrontService.CreateOperatorAsync(user.Login, user.Password, user.FirstName, user.LastName, user.ValidUntil, user.Role, user.Comment);
    return new CreatedAtActionResult("Get", "operators", new { id = ((Operator)op).Id }, op);
}

这篇关于ASP.NET Core MVC-模型绑定:使用属性[FromBody](BodyModelBinder)绑定接口模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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