我想根据主体内容和标题内容填充 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/