【问题标题】:How to pass object to web api?如何将对象传递给 Web api?
【发布时间】:2018-07-24 21:06:38
【问题描述】:

我在下面有一个 GET API 方法的代码。

我无法发送对象参数并让 API 方法使用它。 API方法被调用,但参数始终为null。

问:如何更改代码以接收对象输入?

一般来说,我想我不应该使用 GET 请求发送对象?但我认为这是可能的?

我尝试过使用 [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 请求没有正文,这是一个 POST
  • 并更改方法名称以发布确实可以修复它。但是我的方法确实是一个get——把它转换成POST不会错吗?我在想 POST 保留用于创建,PUT 用于更改,GET 用于检索?
  • Get Req 没有​​ body ... 像这样尝试public IHttpActionResult Get([ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] GetProductBasesRequest getProductBasesRequest)
  • @UmerZaman -- 请重新评论作为解决方案,我会接受。它确实回答了我关于如何做到这一点的问题。然而,这会使事情复杂化,我会选择重写到发布选项。谢谢大家,快速回复!

标签: c# get asp.net-web-api2


【解决方案1】:

Get Req 没有​​实体...试试这样

public IHttpActionResult Get([ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] GetProductBasesRequest getProductBasesRequest)

public IHttpActionResult Get([FromUri] GetProductBasesRequest getProductBasesRequest)

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2023-03-03
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多