gpt4 book ai didi

c# - 不使用模型类直接将 int 发布到 web api

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:05 24 4
gpt4 key购买 nike

我是 C# 新手。我尝试使用 int 创建一个邮政服务。所有获取和发布服务都运行良好。

但是当我将参数传递给后期服务时,它始终为空。但是在创建一个类之后它工作正常。我们可以直接将 int 传递给服务,还是必须为其创建一个模型类?

    [System.Web.Http.HttpPost]
public IHttpActionResult GetUserByID(int id)
{
var user = userList.FirstOrDefault((p) => p.Id == id);
if (user== null)
{
return NotFound();
}
return Ok(user);
}

但它总是发送 0 。但是当我创建一个类并将该 int 添加为属性时,它工作正常。

工作代码

    [System.Web.Http.HttpPost]
public IHttpActionResult GetUserByID(data id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok();
}

public class data
{
[Required]
public int id { get; set; }
}

编辑

are my header accurate?

enter image description here

最佳答案

我认为你需要在参数中添加[FromBody]:

[System.Web.Http.HttpPost]
public IHttpActionResult GetUserByID([FromBody]int id)
{
var user = userList.FirstOrDefault((p) => p.Id == id);
if (user== null)
{
return NotFound();
}
return Ok(user);
}

根据文档:Parameter Binding in ASP.NET Web API

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

它接着说:Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter

更新 - 让 [HttpPost] 工作...

正如@Shahbaz 在下面建议的那样,确保您已将 Content-Type header 设置为 application/json,否则您将收到错误消息:

The request entity's media type 'text/plain' is not supported for this resource.

此外,请确保您在请求正文仅发布id,例如1,而不是将包装在 JSON 对象中的 id 作为键/值对发布 { "id": "1"}

最后 - 考虑改用 [HttpGet]...

值得指出的是,因为您现在只是发送一个 int获取 一条记录,即使您可以使用 [HttpPost ],最好还是将其更改为 [HttpGet],这在语义上是正确的 - 您正在获取用户记录,实际上并不需要发布任何内容。所以这样的事情可能会更好:

[System.Web.Http.HttpGet]
[Route("api/users/{id}")]
public IHttpActionResult GetUserByID(int id)
{
var user = userList.FirstOrDefault((p) => p.Id == id);
if (user== null)
{
return NotFound();
}
return Ok(user);
}

然后把你的 id 放在请求的 URL 中,像这样:

https://yourdomain/api/users/1

上面的例子使用了Attribute Routing这可以帮助您创建自己的自定义 URL 以针对您自己的 API 操作方法。

关于c# - 不使用模型类直接将 int 发布到 web api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45814635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com