C# 当我需要使用具有多个参数的POST方法而不是单独的模型时?
您能告诉我什么时候需要在WebApi/MVC应用程序中使用多个参数而不是单独的模型吗 我有一个动作需要几个参数C# 当我需要使用具有多个参数的POST方法而不是单独的模型时?,c#,asp.net-web-api,model-binding,C#,Asp.net Web Api,Model Binding,您能告诉我什么时候需要在WebApi/MVC应用程序中使用多个参数而不是单独的模型吗 我有一个动作需要几个参数 [HttpPost] public InfoViewModel GetInfo(IEnumerable<Guid> Ids, DocumentType type) { // to do smth } 第二种情况我需要一个特殊型号 public class RequestViewModel { public IEnumerable<Guid> I
[HttpPost]
public InfoViewModel GetInfo(IEnumerable<Guid> Ids, DocumentType type)
{
// to do smth
}
第二种情况我需要一个特殊型号
public class RequestViewModel
{
public IEnumerable<Guid> Ids { get; set; }
public DocumentType DocumentType { get; set; }
}
公共类RequestViewModel
{
公共IEnumerable ID{get;set;}
公共DocumentType DocumentType{get;set;}
}
我以JSON格式将数据发送到服务器。你能告诉我这两种方法的优缺点吗?谢谢。ASP.NET Web API和MVC将尝试绑定操作方法的参数,如下所示
- Web API-默认情况下从请求主体绑定。但这仅限于一个参数,即Web API将使用MediaTypeFormatter(简单地说是序列化程序)将请求主体JSON绑定到一个复杂类型参数。这是因为请求主体在默认情况下存储在非缓冲流中,可以读取一次。剩余的复杂类型参数(如果有)只能通过将其应用于参数来使用任何绑定属性(例如[FromUri]、[ModelBinder])进行绑定
- MVC-从任何地方绑定,即请求正文、路由/查询字符串数据。这是因为与Web API使用的MediaTypeFormatter相比,它默认使用ModelBinder
- Web API-默认情况下从路由/查询字符串数据(即从URI)绑定。但可以通过对参数应用[FromBody]属性或某些类型转换器,强制它们从body绑定
- MVC-从任何地方绑定,即请求正文、路由/查询字符串数据。这是因为它默认使用ModelBinder
public class RequestViewModel
{
public IEnumerable<Guid> Ids { get; set; }
public DocumentType DocumentType { get; set; }
}