我有一个暴露此功能的asp.net核心(v2.1)webapi项目:
[HttpPost]
[Route("v1/do-something")]
public async Task<IActionResult> PostDoSomething(ModelData model)
{
//...
}
和此模型:
public class ModelData
{
[Required]
public string Email { get; set; }
}
从内容类型的角度来看,我想使此端点灵活。因此,可以在正文中发送此终结点不同的内容类型。
例如,将允许使用那些“ BODY”参数:
// application/x-www-form-urlencoded
email="abc123@gmail.com"
// application/json
{
"email": "abc123@gmail.com"
}
与旧的.net框架相反,在dotnet核心中不允许开箱即用。我发现我需要将Consume
属性添加到[FormForm]
属性中。但是,如果我在模型参数中添加[FormForm]
属性,它将无法在JSON上运行(例如)-因为那时它应该是[FromBody]
。
尽管我可以使用如下代码:
[HttpPost]
[Route("v1/do-something")]
public async Task<IActionResult> PostDoSomething([FromBody] [FromForm] ModelData model)
{
//...
}
但是,正如您所料,此代码无法正常工作。
因此,为了获得这种灵活性,我必须复制所有端点-这听起来像是一个非常非常糟糕的主意。
[HttpPost]
[Route("v1/do-something")]
[Consume ("application/json")]
public async Task<IActionResult> PostDoSomething([FromBody] ModelData model)
{
//...
}
[HttpPost]
[Route("v1/do-something")]
[Consume ("application/x-www-form-urlencoded")]
public async Task<IActionResult> PostDoSomething([FromForm] ModelData model)
{
//...
}
// ... Other content types here ...
听起来很容易。但是似乎更复杂。
我错过了什么?如何使端点可以在任何内容类型中工作?
答案 0 :(得分:4)
这里是a custom model binder,它根据内容类型进行绑定。
public class BodyOrForm : IModelBinder
{
private readonly IModelBinderFactory factory;
public BodyOrForm(IModelBinderFactory factory) => this.factory = factory;
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var contentType =
bindingContext.ActionContext.HttpContext.Request.ContentType;
BindingInfo bindingInfo = new BindingInfo();
if (contentType == "application/json")
{
bindingInfo.BindingSource = BindingSource.Body;
}
else if (contentType == "application/x-www-form-urlencoded")
{
bindingInfo.BindingSource = BindingSource.Form;
}
else
{
bindingContext.Result = ModelBindingResult.Failed();
}
var binder = factory.CreateBinder(new ModelBinderFactoryContext
{
Metadata = bindingContext.ModelMetadata,
BindingInfo = bindingInfo,
});
await binder.BindModelAsync(bindingContext);
}
}
通过以下操作进行了测试。
[HttpPost]
[Route("api/body-or-form")]
public IActionResult PostDoSomething([ModelBinder(typeof(BodyOrForm))] ModelData model)
{
return new OkObjectResult(model);
}