I have a controller defined as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MissingClinics.Controllers
{
[RoutePrefix("api/appointment")]
public class AppointmentController : ApiController
{
[HttpPost]
public IHttpActionResult GetMissingKeys([FromBody]String MRNList)
{
return Ok();
}
}
}
and the following JavaScript calls that page.
try {
$.ajax({
type: 'POST',
url: '/api/Appointment/GetMissingKeys',
data: $('#mrnList').val(),
dataType: 'text'
}).done(function () {
alert('done!');
}).fail(function (Status, errorThrown) {
alert('Error: ' + Status.status + ' - ' + Status.statusText);
}).always(function () {
alert('All done or not');
});
}
catch (e) {
alert(e);
}
WebApi.config is the following
namespace MissingClinics
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
RouteConfig.cs
namespace MissingClinics
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Now because I am going to be passing a fair amount of data I need to pass it in the body (rather than as part of the Url).
But in the Call it is returning Error 405 - Method not allowed. But from what I can see jquery should be making a post request and the controller is accepting a post - so why the Method not allowed?
[AllowHtml]Attribute in you param.[Route("GetMissingKeys")]on your method.dataType: 'text'attribute or specifying other types like 'application/json' etc? Also did you try hitting the api from some debugging tool like Fiddler or Advanced Rest Client for Chrome browser and see what is going on?