CodeMonkey
CodeMonkey

Reputation: 12444

415 Unsupported Media Type in ASP.NET core web api

I am trying to experiment with asp.net core web api so I made some simple api with a controller like this:

[ApiController]
[Route("MyController")]
public class MyController : ControllerBase
{
    [HttpGet]
    [Route("GetResult")]
    public IActionResult GetResult(string param1, string param2= null, SomeClassObj obj = null)
    {  .... }
}

I ran the api locally and sent this postman GET request:

https://localhost:5001/MyController/GetResult?param1=someString

I got the error: 415 Unsupported Media Type

What am I missing here so it could work?

Upvotes: 7

Views: 18711

Answers (3)

KingRaja
KingRaja

Reputation: 194

I was getting the same error after invoking the WEB API from .NET MVC. As suggested by @zhulien, I have changed from [FromBody] to [FromForm] in WebAPI, it works fine for me.

.NET Core WebAPI method.

public async Task<IActionResult> Login([FromForm] LoginModel loginInfo)
    { // JWT code here }

.Net Core MVC Action Method.

public async void InvokeLoginAPIAsync(string endPoint, string userName, string pwd)
    {
        configuration = new ConfigurationBuilder()
              .AddJsonFile("appsettings.json")
              .Build();
        baseUrl = configuration["Application:BaseAPI"] ?? throw new Exception("Unable to get the configuration with key Application:BaseAPI");

        string targetUrl = string.Format("{0}/{1}", baseUrl, endPoint);

        using (HttpClient deviceClient = new HttpClient())
        {
            var request = new HttpRequestMessage(HttpMethod.Post, targetUrl);

           var data = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("userName", userName),
                new KeyValuePair<string, string>("password", pwd)
            };

            request.Content = new FormUrlEncodedContent(data);

            using (var response = await deviceClient.SendAsync(request))
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    TempData["Response"] = JsonConvert.SerializeObject(response.Content);
                }
            }
        }
    }

Upvotes: 11

Subhash Makkena
Subhash Makkena

Reputation: 1969

Use [FromForm] attribute before each argument in the controller function.

Upvotes: 3

zhulien
zhulien

Reputation: 5715

Which version of .NET Core are you using?

Try doing the request from the browser and see if you have the same result.

Also, are you sure you're doing a GET and not a POST request in Postman? You shouldn't get 415 errors for GET requests, especially when you're not sending any body. This error mainly occurs when you try to send a body and you haven't specified the media-type through the Content-Type header.

Ensure that the request is GET and your body is empty.

Solution after post edit:

As you're trying to parse a DTO object(SomeClassObj), you should specify where the values should come from. In order to fix your specific case, add the [FromQuery] attribute before SomeClassObj.

Your code should look like this:

[ApiController]
[Route("MyController")]
public class MyController : ControllerBase
{
    [HttpGet]
    [Route("GetResult")]
    public IActionResult GetResult(string param1, string param2= null, [FromQuery]SomeClassObj obj = null)
    {  .... }
}

This tells the parser to fetch the data from the query string. This will fix the 415 issue. However, if you want to bind to complex types, especially on get, checkout those topics: ASP.NET CORE 3.1 Model Binding and this issue as you will most probably encounter issues with parsing your DTO object.

Upvotes: 9

Related Questions