POSTMAN发送POST请求返回Unsupported Media Type问题求助
Hey there, let's dig into that "Unsupported Media Type" error you're hitting with your POST request in Postman. I've worked through similar issues with ASP.NET Core MVC 2 APIs before, so here are the most common fixes to check off:
1. Double-Check the Content-Type Request Header
ASP.NET Core MVC 2 needs clear instructions on how to parse your request body. If you're sending JSON data (the standard for APIs), make sure you've set the right header in Postman:
- Head to the Headers tab in Postman
- Add a key-value pair:
Content-Type: application/json - Without this header, the server has no clue how to interpret the data you're sending, which triggers the 415 Unsupported Media Type error instantly.
2. Finish Adding the [FromBody] Attribute to Your Post Method
Looking at your code snippet, you started typing [F... — I’m guessing that’s supposed to be the [FromBody] attribute! In ASP.NET Core MVC 2, you must explicitly mark complex-type parameters with this attribute to tell the framework to bind them from the request body. Here’s what your complete Post method should look like:
[HttpPost] public Reservation Post([FromBody] Reservation reservation) { // Add your logic to save the reservation to the repository repository.Reservations.Add(reservation); // Don't forget to persist changes if your repository requires it return reservation; }
Without [FromBody], the framework will try to pull values from the URL or form data instead of the request body, leading to a media type mismatch.
3. Validate Your Request Body Format
Even with the right header and attribute, a malformed request body can cause this error. Double-check your JSON in Postman’s Body tab (make sure you’ve selected the raw option and set the format to JSON):
- Fix any syntax errors (like missing commas, unclosed quotes, or trailing commas)
- Match the property names in your JSON to the
Reservationclass properties (ASP.NET Core is case-insensitive by default, but consistency avoids headaches)
Example of a valid request body:
{ "name": "Jane Smith", "date": "2024-06-15T10:00:00", "partySize": 4 }
4. Confirm Your Startup Configuration
Make sure your Startup.cs is properly set up to handle JSON serialization. In the ConfigureServices method, you should have:
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddJsonOptions(options => { // Optional: Tweak JSON settings (e.g., ignore circular references) options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); }
If AddMvc() isn’t called, or JSON serialization isn’t configured, the server can’t parse incoming JSON requests at all.
Start with these checks — they cover 90% of the cases where this error pops up in ASP.NET Core MVC 2 APIs.
内容的提问来源于stack exchange,提问作者coolhand

