[英]Post request to WebAPI2
I writing REST service using WebAPI2 我使用WebAPI2编写REST服务
I need to add book to db. 我需要将书添加到数据库。
I have this code Model: 我有此代码模型:
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public int Year { get; set; }
}
And Controller: 和控制器:
[HttpPost]
public void CreateBook([FromBody]Book book)
{
db.Books.Add(book);
db.SaveChanges();
}
I try to send POST request from postman 我尝试从邮递员发送POST请求
But I have this error 但是我有这个错误
"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 'Book' from content with media type 'multipart/form-data'." “消息”:“此资源不支持请求实体的媒体类型'multipart / form-data'。”,“ ExceptionMessage”:“没有MediaTypeFormatter可用于从媒体类型为'的内容读取'Book'类型的对象多部分/表单数据”。
How I can hadle it? 我怎么能哭呢?
You are getting this error because the Content-Type
header being sent with the request is multipart/form-data
instead of application/json
. 之所以收到此错误,是因为与请求一起发送的Content-Type
标头是multipart/form-data
而不是application/json
。 This is happening because you have selected the "form-data" radio button in Postman, which automatically sets the Content-Type
to multipart/form-data
regardless of whether you have entered a header manually. 发生这种情况是因为您在Postman中选择了“表单数据”单选按钮,该按钮自动将Content-Type
为multipart/form-data
而不管是否手动输入了标题。 (This is covered in the documentation -- see "Note about headers" in the "Request Body" section about 2/3 of the way down the page.) Try selecting "raw" instead, and ensure you have added a Content-Type
header with a value of application/json
. (这已在文档中进行了介绍 -请参阅“请求Content-Type
”部分中的“关于标头的说明”,大约位于页面的2/3下方。)尝试选择“原始”,并确保添加了Content-Type
标头,其值为application/json
。 Then, add your JSON in the Body section. 然后,在“正文”部分添加您的JSON。
{
"Id": 1234,
"Name": "A Book About Nothing",
"Author": "Joe Schmoe",
"Year": 1993
}
you have to add a formatter to the HttpConfiguration object, if this is an ASP.NET MVC project, you will find it in the WebApiConfig.cs class under the Register method 您必须向HttpConfiguration对象添加一个格式化程序,如果这是一个ASP.NET MVC项目,则可以在Register方法下的WebApiConfig.cs类中找到它。
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Routes
config.Routes.MapHttpRoute(/// your routes);
//Formatters
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.