c# - FromBody 和 FromHeader 在模型上混合使用,不绑定(bind)所有值

标签 c# asp.net-core model-binding

我想根据主体内容和标题内容填充 View 模型,我尝试使用这两个属性进行装饰,但似乎只有一个或另一个正在运行并填充值。

将 FromBody 移动到属性会导致填充 header 值,将 FromBody 放在 Controller 上的参数声明中会导致填充主体 Id。

随后在 Controller 中运行 TryUpdateModelAsync 确实会填充两者,但这看起来很丑陋并且太过分了。

有人知道如何让它发挥作用吗?

public IActionResult GetAddress([FromBody]AddressDataViewModel model)
{
    if (!this.ModelState.IsValid)
    {
        return this.BadRequest(this.ModelState);
    }

    return this.Ok(this.helper.GetAddress(model.Id));
}

public class AddressDataViewModel : BaseHttpRequestMeta
{
    [Required]
    public string Id { get; set; }
}


public class BaseHttpRequestMeta 
{
    [BindRequired]
    [FromHeader(Name = "sessionid")]
    public string SessionId { get; set; }
}

最佳答案

您可以尝试制作自己的绑定(bind)源。还没有测试过这个,但是类似混合绑定(bind)源:

public class FromHeaderOrBodyAttribute : Attribute, IBindingSourceMetadata
{
    public BindingSource BindingSource => new HeaderOrBodyBindingSource();
}

public class HeaderOrBindingSource : BindingSource
{
    public HeaderOrBindingSource() : base("HeaderOrBody", "Header or Body binding source", true, true)
    {
    }

    public override bool CanAcceptDataFrom(BindingSource bindingSource)
    {
        return bindingSource == BindingSource.Header
            || bindingSource == BindingSource.Body;
    }
}

然后在您的操作中使用该属性:

public IActionResult GetAddress([FromHeaderOrBody]AddressDataViewModel model)
{
}

同样,还没有测试过这个,但我认为代码对于评论来说有点太多了。请回复您的结果。

关于c# - FromBody 和 FromHeader 在模型上混合使用,不绑定(bind)所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46220552/

相关文章:

c# - 如何将 Quartz.NET 与 ASP.NET Core Web 应用程序一起使用?

c# - scafford 自动生成 crud 仓库 asp.net5

asp.net - 无法在 helloweb 演示应用程序上运行 k run

c# - 在 WebAPI 中绑定(bind)抽象操作参数

c# - 从 header Asp.Net Core WebApi 绑定(bind)自定义对象

angularjs - 使用自动 ng-bind 创建 ASP MVC 自定义 View

c# - 如何确定设置了哪个位

c# asp.net core Bearer错误="invalid_token"

c# - 如何将System.Windows dll添加到Visual Studio 2010 Express?

c# - 如何从另一个 .net API 调用 .net API?