我一直在使用2.2中的Web api,使用对象的post方法或使用基元的get方法都没有问题。我的问题是我想同时从路由中的值和查询字符串值的get方法绑定到模型对象。
所以基本上从下面的代码中,我想绑定到一个简单的对象。如果您认为网址是:
http://localhost:9999/api/Values/ {名字}?{Surname} = Bob
我尝试装饰模型对象,并收到415个看起来很奇怪的响应
using Microsoft.AspNetCore.Mvc;
namespace apitest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values/5
[HttpGet("{Firstname}")]
public ActionResult<string> Get(Person person)
{
return "value";
}
}
}
namespace apitest
{
public class Person
{
public string Firstname { get; set; }
public string Surname { get; set; }
}
}
显然,该示例是琐碎且荒谬的,但基本上我只想从Person对象上的first / name属性来从route / querystring映射Firstname和Surname。我必须编写自定义模型联编程序吗?如果是这样,那有什么很棒的例子吗?
答案 0 :(得分:0)
对于您的问题,这是由OnTaskRemoved()
引起的。
SuppressInferBindingSourcesForParameters
像
一样在//
// Summary:
// Options used to configure behavior for types annotated with Microsoft.AspNetCore.Mvc.ApiControllerAttribute.
public class ApiBehaviorOptions : IEnumerable<ICompatibilitySwitch>, IEnumerable
{
//
// Summary:
// Gets or sets a value that determines if model binding sources are inferred for
// action parameters on controllers annotated with Microsoft.AspNetCore.Mvc.ApiControllerAttribute
// is suppressed.
// When enabled, the following sources are inferred: Parameters that appear as route
// values, are assumed to be bound from the path (Microsoft.AspNetCore.Mvc.ModelBinding.BindingSource.Path).
// Parameters of type Microsoft.AspNetCore.Http.IFormFile and Microsoft.AspNetCore.Http.IFormFileCollection
// are assumed to be bound from form. Parameters that are complex (Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata.IsComplexType)
// are assumed to be bound from the body (Microsoft.AspNetCore.Mvc.ModelBinding.BindingSource.Body).
// All other parameters are assumed to be bound from the query.
public bool SuppressInferBindingSourcesForParameters { get; set; }
中配置此值
Startup.cs
答案 1 :(得分:0)
已经有一段时间了,但是也许有人在ASP.NET Core 3.1中遇到同样的问题,所以我将保留我的答案:)
使用[FromQuery]属性标记person参数,并使用[FromRoute]属性标记Firstname属性。
所以它应该像这样:
namespace apitest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values/5
[HttpGet("{Firstname}")]
public ActionResult<string> Get([FromQuery] Person person)
{
return "value";
}
}
}
namespace apitest
{
public class Person
{
[FromRoute]
public string Firstname { get; set; }
public string Surname { get; set; }
}
}