自定义模型绑定器在 Web API 中返回空对象



我在 web api 中使用自定义模型绑定器,但我的模型值为空。

它无法从ValueProvider获取值。

请查看下面的代码。

bindingContext.ValueProvider.GetValue("Report") is null

这是我的代码。

public class TestReportDto
{
public ReportFormatType ExportFormat { get; set; }
public string Report { get; set; }
public Dictionary<string, object> ParameterValues { get; set; }
}
public enum ReportFormatType
{
PDF,
XLS
}

我的模型绑定器类。

public class TestModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var testReportDto = new TestReportDto();
bool isSuccess = true;
if (bindingContext.ValueProvider.GetValue("Report") != null)
{
testReportDto.Report = Convert.ToString(bindingContext.ValueProvider.GetValue("Report").RawValue);
}
else
{
isSuccess = false;
bindingContext.ModelState.AddModelError("request.Report", "Report");
}
bindingContext.Model = testReportDto;
return isSuccess;
}
}

原料药代码:

public async Task<string> Post([ModelBinder(typeof(TestModelBinder))]TestReportDto request)
{
return "Hello";
}

可以从自定义模型绑定器中 HttpActionContext 对象的 Request 对象获取值。我使用的示例如下。

var bodyContent = actionContext.Request.Content.ReadAsStringAsync().Result;

请注意,这是您面临的问题的快速而肮脏的解决方案。如果您遵守规则,那么您应该创建用于处理此类数据(正文内容(的提供程序类,然后创建一个工厂类来正确参与整个过程。就像这里描述的那样。

最新更新