ProfK
ProfK

Reputation: 51064

Why do I get an Unsupported Media Type on this request?

I am making the below request from a WPF app to an MVC Core app that acts as an API:

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("userName", userName),
    new KeyValuePair<string, string>("password", password)
});

////var content = new StringContent($"{{\"username\": {userName}, \"password\": {password}}}", Encoding.UTF8, "application/json");
var resp = await _client.PostAsync("api/Token", formContent);
var json = await resp.Content.ReadAsStringAsync();
var tw = JsonConvert.DeserializeObject<TokenWrapper>(json);
return tw.Token;

When I inspect resp with a breakpoint, after the PostAsync call, I see a 415 - Unsupported Media Type error. A breakpoint on the first line of the action isn't event hit, so I think the request isn't even reaching the controller.

The controller action looks like this:

  public async Task<string> LoginAsync(string userName, string password)
 {
    var formContent = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("userName", userName),
        new KeyValuePair<string, string>("password", password)
    });

    ////var content = new StringContent($"{{\"username\": {userName}, \"password\": {password}}}", Encoding.UTF8, "application/json");
    var resp = await _client.PostAsync("api/Token", formContent);
    var tempContent = await resp.Content.ReadAsStringAsync();
    var json = await resp.Content.ReadAsStringAsync();
    var tw = JsonConvert.DeserializeObject<TokenWrapper>(json);
    return tw.Token;
}

I would expect FormUrlEncodedContent to imply the content type and work, as in the high number of examples I have seen like this. Why am I getting this 415 error?

Upvotes: 1

Views: 749

Answers (1)

Shaiju T
Shaiju T

Reputation: 6609

Try by setting the Media Typeas below:

var content = new StringContent(formContent.ToString(), Encoding.UTF8, "application/json");

var result = await _client.PostAsync("http://example.com/api/Token", content);

Also PostAsync accepts parameters of requestUri and content , your code is the missing Absolute requestUri.

Upvotes: 1

Related Questions