Paul S Chapman
Paul S Chapman

Reputation: 832

Method not allowed doing a post in WebAPI

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?

Upvotes: 0

Views: 257

Answers (3)

programmer.zheng
programmer.zheng

Reputation: 13

Have you changed the default route from api/{action} to api/{controller}/{action}/{id}?

ASP.NET WEB API select action with request HTTP method,there are two ways below:

1.Change the web api default route

WebApiConfig.cs

config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
With this ,you do not need to change you html file.

2.Change your action name

public IHttpActionResult Post([FromBody]String MRNList)

and call javascript like this :

$.ajax("/api/Appointment", {type:"POST", data:$("").val() ... }

Upvotes: 0

MrBliz
MrBliz

Reputation: 5898

Been a while since i've used jquery but

Shouldn't this

data: $('#mrnList').val(),

be this

data : {mrnList: $('#mrnList').val()}, //Or MrnList depending on your jsonformatting options

Also the dataType should be 'json' i think.

Have you tried adding [Route("GetMissingKeys")] to your method?

Upvotes: 1

Andrii Tsok
Andrii Tsok

Reputation: 1446

With the default routing template, Web API uses the HTTP method to select the action. However, you can also create a route where the action name is included in the URI:

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Routing instructions

Upvotes: 1

Related Questions