0
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?

5
  • is there HTML in your request data , if so use [AllowHtml] Attribute in you param. Commented Nov 3, 2015 at 16:42
  • not sure if attribute routing will default to your method name...Try [Route("GetMissingKeys")] on your method. Commented Nov 3, 2015 at 16:44
  • No HTML and I have tried the Route Attribute as well Commented Nov 3, 2015 at 16:56
  • @PaulSChapman Did you try excluding the 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? Commented Nov 3, 2015 at 17:11
  • This is utter speculation, but it might be that WebAPI is getting it's conventions confused because your Method is prefixed with Get. I'd have to check the source to be sure. Commented Nov 3, 2015 at 17:46

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I've tried that - even reversing the order of the Route and HttpPost - even tried AcceptVerb
@PaulSChapman could you please add your Startup class implementation to your main topic ? Will try to figure out what is wrong.
@PaulSChapman i've changed and added some additional information to my answer. In the end of article you can find information about: Routing by Action Name. Take a look to this.
1

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?

Comments

0

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() ... }

1 Comment

Not sure what you meant but did try changing the url in the RouteConfig.cs but that did not seem to make a difference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.