Search code examples
c#.net-coreasp.net-core-webapi

Receive Error StatusCode 415 when try to POST to an endpoint in C# ASP.NET Core Web API


I have an ApiTester in HomeController. When ApiTester loaded, it will make a POST request to an API method in AuthController.

Home Index page contains Link to try the api:

<a href="@Url.Action("ApiTester", "Home")">ApiTester Click Here</a>

This is my HomeController class:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using TestWebApplication.Models;

namespace TestWebApplication.Controllers
{
    public class HomeController : Controller
    {

        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> ApiTester()
        {
            var client = new HttpClient();
            var values = new Dictionary<string, string> { { "Name", "Alice" } };
            var content = new FormUrlEncodedContent(values);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var response = await client.PostAsync("https://localhost:7284/api/Auth/ApiTest", content);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                ViewBag.ApiResponse = result;
            }
            else
            {
                ViewBag.ApiResponse = "Error: " + response.StatusCode;
            }

            return View();
        }
    }
}

This is the AuthController class:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace TestWebApplication.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        [HttpGet("GetTest")]
        public IActionResult GetTest()
        {
            return Ok(new { message = "Get Test Succesfull!" });
        }

        [HttpPost("ApiTest")]
        public IActionResult ApiTest([FromBody] Dictionary<string, string> values)
        {
            string name = values["name"];
            return Ok(new { message = "200: Post Test Succesfull!" });
        }
    }
}

Nothing fancy in my program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

I receive the Error:UnsupportedMediaType. What could be causing this? When I remove the ApiTest val like this:

public IActionResult ApiTest()
.
.

It runs smoothly.


Solution

  • Try modify your HttpPost method in the following way:

            [HttpPost("ApiTest")]
            [Consumes("application/x-www-form-urlencoded")]
            public IActionResult ApiTest([FromForm] Dictionary<string, string> values)
            {
                string name = values["name"];
                return Ok(new { message = "200: Post Test Succesfull!" });
            }
    

    Note Consumes attribute and FromBody becoming FromForm