CodexBloom - Programming Q&A Platform

ASP.NET Core 6 Web API: 415 Unsupported Media Type when posting JSON with custom headers

๐Ÿ‘€ Views: 224 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-05-31
asp.net-core web-api json http-415 csharp

I'm sure I'm missing something obvious here, but I tried several approaches but none seem to work..... I'm currently developing a Web API using ASP.NET Core 6 and I'm encountering a `415 Unsupported Media Type` error when trying to post JSON data that includes custom headers. I have a client-side application developed in React that sends a POST request to my API endpoint. The request looks something like this: ```javascript fetch('https://myapi.com/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'MyValue' }, body: JSON.stringify({ name: 'Item Name', value: 100 }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` On the server side, I have configured the API to accept JSON content with the following setup in my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` I've confirmed that the API endpoint is correctly set up to handle `application/json`, and I even added a `[FromBody]` attribute to my action method: ```csharp [HttpPost] public IActionResult PostItem([FromBody] Item item) { if (item == null) return BadRequest("Item cannot be null"); return CreatedAtAction(nameof(GetItem), new { id = item.Id }, item); } ``` Despite this, I keep receiving the error when I try to post. Iโ€™ve also checked the request format and the network tab in my browserโ€™s developer tools, and it seems the request is being sent as expected. What might I be missing here? Is there a specific configuration I need to double-check to ensure my API accepts requests with custom headers? Any insights would be greatly appreciated! I'm working on a API that needs to handle this. Am I missing something obvious? I'm developing on Windows 11 with Csharp. Any suggestions would be helpful. This is happening in both development and production on Ubuntu 22.04.