[英]Postman returns 415 when trying to do a POST using form-data, but the same request with JSON works fine
I'm building a REST API and testing it out using Postman.我正在构建一个 REST API 并使用 Postman 对其进行测试。 I have an end-point which works fine when I test it by sending in raw json data, but I want to expand on this endpoint and allow it to take both json data and accept a file, so I wanted to test my current endpoint without any modifications, and see if I would get back the same result when I test my API using form-data instead of JSON, but it always throws a 415 exception.
我有一个端点,当我通过发送原始 json 数据来测试它时工作正常,但我想扩展这个端点并允许它同时获取 json 数据并接受一个文件,所以我想测试我当前的端点而不任何修改,看看当我使用表单数据而不是 JSON 测试我的 API 时是否会得到相同的结果,但它总是抛出 415 异常。
On this picture I make a request with form-data.在这张图片上,我使用表单数据发出请求。
And here I make the request to the same endpoint but with json data在这里我向同一个端点发出请求,但使用 json 数据
Note that I have not added any customs headers when sending the requests, the (10) you see in the top is Temporary Headers.请注意,我在发送请求时没有添加任何海关标头,您在顶部看到的 (10) 是临时标头。 I also tried adding Content-Type: multipart/form-data, but got the same result.
我也尝试添加 Content-Type: multipart/form-data,但得到了相同的结果。
Here's the code behind这是后面的代码
PeopleController.cs人员控制器.cs
[HttpPost]
public ActionResult<PersonDto> PostPerson(PersonForCreationDto person)
{
var personEntity = _mapper.Map<Entities.Person>(person); //Maps PersonForCreationDto to Entites.Person. This is possible because of the mapping in PeopleProfile.cs
_personLibraryRepositry.AddPerson(personEntity);
_personLibraryRepositry.Save();
var personToReturn = _mapper.Map<PersonDto>(personEntity);
return CreatedAtRoute("GetPerson",
new { personId = personToReturn.PersonId },
personToReturn);
}
PersonForCreationDto创造者
public class PersonForCreationDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string ReasonsForBeingOnTheList { get; set; }
public ICollection<PictureForCreationDto> Pictures { get; set; }
= new List<PictureForCreationDto>();
}
PersonLibraryRepository.cs PersonLibraryRepository.cs
public void AddPerson(Person person)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.PersonId = Guid.NewGuid(); //API is responsibile for creating new IDS.
foreach (var picture in person.Pictures)
{
picture.PictureId = Guid.NewGuid();
}
_context.People.Add(person);
}
在您的表单数据中,将此添加到标题
Content-Type: application/json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.