如何为POST方法设置webapi控制器

本文关键字:设置 webapi 控制器 方法 POST | 更新日期: 2023-09-27 18:14:45

我试图使一个POST服务,返回Tienda的列表。我的代码是这样的:

[HttpPost]
[ResponseType(typeof(List<TiendaWrapper>))]
public IHttpActionResult GetTiendasPost([FromBody]Tienda t)
{
    List<Tienda> ListaTiendas = db.Tiendas.ToList();
    List<TiendaWrapper> lstTiendas = new List<TiendaWrapper>();
    foreach(Tienda T in ListaTiendas)
    {
        if (T.CodDpto == t.CodDpto && T.CodRetail == t.CodRetail)
        {
            TiendaWrapper tiend = new TiendaWrapper(T);
            lstTiendas.Add(tiend);
        }
    }
    return Ok(lstTiendas);
}

但是当我使用Postman调用服务时,我得到了这个异常。该函数应该接收两个Id作为主体,并找到具有这些Id的Tiendas

"$id": "1",
  "Message": "The request entity's media type 'multipart/form-data' is not supported for this resource.",
  "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Tienda' from content with media type 'multipart/form-data'.",
  "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",

任何帮助都将是伟大的,提前感谢你。

编辑:

这就是我在Postman: http://localhost:1918/api/tiendas/GetTiendasPost中调用方法的方式然后我将Body中的值添加为form-data。

如何为POST方法设置webapi控制器

在HTTP请求中需要设置Content-Type为:Content-Type: application/json

如果您将body作为表单数据传递,那么您应该使用application/x-www-form-urlencoded作为媒体类型。当然,除非你真的要发送多部分数据。但是,我不确定WebAPI是否默认设置为处理多部分表单。