Asp.net 参数绑定对象[FromBody]不是可选的
我正在使用WebAPI和Swashback来测试和生成客户机代码。 在我的web应用程序中,我有一个对象作为参数的方法:Asp.net 参数绑定对象[FromBody]不是可选的,asp.net,asp.net-web-api,swagger,swashbuckle,Asp.net,Asp.net Web Api,Swagger,Swashbuckle,我正在使用WebAPI和Swashback来测试和生成客户机代码。 在我的web应用程序中,我有一个对象作为参数的方法: [Route("Orders/SendReport")] [HttpPost] public HttpResponseMessage Orders(string email,[FromBody]ReportOrders reportOrders){ ... } 在SwaggerUI中,此方法在此对象参数的DataType部分显示以下示例
[Route("Orders/SendReport")]
[HttpPost]
public HttpResponseMessage Orders(string email,[FromBody]ReportOrders reportOrders){
...
}
在SwaggerUI中,此方法在此对象参数的DataType部分显示以下示例:
**Model:**
ReportOrders {
date1 (string, optional),
date2 (string, optional),
status (string, optional),
codformula (string, optional)
}
有没有办法使这些参数(显然是ReportOrders类的属性)不是可选的?这是当前的ReportOrders类:
namespace Myapp.Models
{
public class ReportOrders
{
public DateTime date1 { get; set; }
public DateTime date2 { get; set; }
public string status { get; set; }
public string codformula { get; set; }
}
}
您需要将模型中的属性标记为
[必需]
:
public class ReportOrders
{
[Required]
public DateTime? date1 { get; set; }
[Required]
public DateTime date2 { get; set; }
[Required]
public string status { get; set; }
[Required]
public string codformula { get; set; }
}
我还将DateTimes设置为空,因为否则您无法知道它们是否已填充。您可以将您的
ReportOrders
类定义添加到问题中吗?当然,我已经添加了。我已经找到了(仅在今天)模型需要引用System.ComponentModels.DataAnnotations,并且注释需要是系统DataAnnotations,而不仅仅是Dapper注释[如果您碰巧将Dapper用作ORM](因为VS2017将它们标识为定义模糊的注释。我猜Dapper有一个同名属性?是的,其他系统不会使用该属性,因为它们正在搜索其中的数据注释。