如何将对象传递到网络 api?
How to pass object to web api?
我在下面有 GET API 方法的代码。
我无法发送对象参数并让 API 方法使用它。 API 方法被调用,但参数始终为空。
问:如何更改我的代码以启用接收对象输入?
一般来说,我想我不应该用 GET 请求发送对象?但我认为这是可能的?
我试过使用 [FromBody] 和不使用 [FromBody]。我认为对象不应该是 [FromUri]?
我使用 Swagger 进行调试;示例对象生成得很好,但是当我发送它时,它到达时为 null。
通过 RestSharp 使用我的客户端时的相同行为。
[SwaggerResponseExample(HttpStatusCode.OK, typeof(GetProductBasesRequestExamplesForSwagger))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(string))]
public IHttpActionResult Get([FromBody]GetProductBasesRequest getProductBasesRequest)
{
// transaction id to trace this calculation across processes.
var transactionId = Guid.NewGuid();
using (LogContext.PushProperty("Method", MethodBase.GetCurrentMethod().Name))
using (LogContext.PushProperty("TransactionId", transactionId))
{
try
{
if(getProductBasesRequest==null)
throw new ArgumentNullException(nameof(getProductBasesRequest),"Input can't be null");
Log.Logger.Debug("ProductBase Get : {@GetProductBasesRequest}", getProductBasesRequest);
var content = new GetProductBasesResponse
{
ProductBases = _productBaseRepository.Get()
};
return Ok(content);
}
catch (Exception e)
{
Log.Logger.Error(e, "ProductBases.Get");
return BadRequest(transactionId.ToString());
}
}
}
Get Req 没有 body ... 试试这样
public IHttpActionResult Get([ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] GetProductBasesRequest getProductBasesRequest)
或
public IHttpActionResult Get([FromUri] GetProductBasesRequest getProductBasesRequest)
我在下面有 GET API 方法的代码。
我无法发送对象参数并让 API 方法使用它。 API 方法被调用,但参数始终为空。
问:如何更改我的代码以启用接收对象输入?
一般来说,我想我不应该用 GET 请求发送对象?但我认为这是可能的?
我试过使用 [FromBody] 和不使用 [FromBody]。我认为对象不应该是 [FromUri]?
我使用 Swagger 进行调试;示例对象生成得很好,但是当我发送它时,它到达时为 null。
通过 RestSharp 使用我的客户端时的相同行为。
[SwaggerResponseExample(HttpStatusCode.OK, typeof(GetProductBasesRequestExamplesForSwagger))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(string))]
public IHttpActionResult Get([FromBody]GetProductBasesRequest getProductBasesRequest)
{
// transaction id to trace this calculation across processes.
var transactionId = Guid.NewGuid();
using (LogContext.PushProperty("Method", MethodBase.GetCurrentMethod().Name))
using (LogContext.PushProperty("TransactionId", transactionId))
{
try
{
if(getProductBasesRequest==null)
throw new ArgumentNullException(nameof(getProductBasesRequest),"Input can't be null");
Log.Logger.Debug("ProductBase Get : {@GetProductBasesRequest}", getProductBasesRequest);
var content = new GetProductBasesResponse
{
ProductBases = _productBaseRepository.Get()
};
return Ok(content);
}
catch (Exception e)
{
Log.Logger.Error(e, "ProductBases.Get");
return BadRequest(transactionId.ToString());
}
}
}
Get Req 没有 body ... 试试这样
public IHttpActionResult Get([ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] GetProductBasesRequest getProductBasesRequest)
或
public IHttpActionResult Get([FromUri] GetProductBasesRequest getProductBasesRequest)