Unsupported media type ASP.NET Core Web API
I had this where the receiving controller method was expecting a [FromBody] argument, but the calling service omitted the parameter. At a guess under the hood, a controller method that expects a (serialised) parameter would expect the request content type (MIME) to be application/json - but the HttpClient calling POST/PUT without a parameter does not pass this (maybe just text/html) - and hence we get 415 'Unsupported Media Type'.
This is a CORS issue.
During development it's safe to accept all http request methods from all origins. Add the following to your startup.cs:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//Accept All HTTP Request Methods from all origins
app.UseCors(builder =>
builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
app.UseMvc();
}
See here for more details about CORS.
The header you are sending is wrong. You are sending Content-Type: application/json
, but you have to send Accept: application/json
.
Content-Type: application/json
is what the server must send to the client and the client must send Accept
to tell the server which type of response it accepts.
addNewSalesman: function (newData) {
console.log("service");
console.log(newData)
var deferred = $q.defer();
$http({
method: 'POST',
url: '/api/Salesman',
headers: { 'Accept': 'application/json' }
}, newData).then(function (res) {
deferred.resolve(res.data);
}, function (res) {
deferred.reject(res);
});
return deferred.promise;
}
Should do it. Also see "Content negotiation" on MDN.
Just replace [FromBody]
to [FromForm]
in your controller.