简体   繁体   中英

MVC and Web Api: The requested resource does not support http method 'POST'

So I've looked at all the questions relating to this problem and tried all the suggestions to no avail. I have a solution in Visual Studio 2019 which consists of multiple MVC projects. I want to add a Web Service which I have duly done. All good so far. So I have a call being made to this Web Service using ajax, thus:

            var apiLocation = getHostname(window.location.href, 0) + "/OLBWebService/api/";
            var obj = { "id": $('#salonDDL').val() };

            // populate the services drop down list based on the salon ID
            $.ajax({
                type: "POST",
                headers: {
                            'Content-Type': 'application/json', /*or whatever type is relevant */
                            'Accept': 'application/json' /* ditto */
                        },
                datatype: "json",  
                url: apiLocation + "Service/GetServicesForSalon",
                data: JSON.stringify(obj),  
                success: function (response) {
                    if (response.length > 0) {
                        $('#serviceDDL').empty();
                        var options = '';
                        options += "<option value='0' selected>Please select a service</option>";
                        for (var i = 0; i < response.length; i++) {
                            options += '<option value="' + response[i].Id + '">' + response[i].Name + '</option>';
                        }
                        $('#serviceDDL').append(options);
                    }
                },
                fail: function (error) {
                    alert(error.StatusText);
                }
            });

I currently have my routing in WebApiConfig.cs thus:

            config.MapHttpAttributeRoutes();

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

I set up a controller with methods thus: (the HttpPost is defined as being from the System.Web.Http namespace)

        [HttpPost]
        public IHttpActionResult GetServicesForSalon([FromBody]DefaultParams passedParams)
        {
            List<Service> service = new List<Service>();
            service = _ServiceService.GetServicesBySalonID(passedParams.id);

            try
            {
                return Json(service.Select(s => new { Id = s.ID, Name = s.Description }).OrderBy(s => s.Name));
            }
            catch (Exception ex)
            {
                _loggingService.LogError(ex, "Error in GetServicesForSalon with id of:" + passedParams.id.ToString());
                return null;
            }
        }

The DefaultParams being passed in are defined thus:

    public class DefaultParams
    {
        public int id { get; set; }
    }

When I run it, either in debug mode via Visual Studio 2019 or using Fiddler, I get the message "The requested resource does not support http method 'POST'".

The strange thing is I have an ajax call prior to this one which works. (the syntax is the original one I always use and I have tried this syntax in the problem call)

            $.ajax({  
                type: "POST",  
                url: apiLocation + "Salon/GetSalonsByOrg",  
                data: JSON.stringify(obj),  
                contentType: "application/json",  
                datatype: "json",  
                success: function (response) {
                    if (response.length > 0) {
                        $('#salonDDL').empty();
                        var options = '';
                        options += "<option value='0' selected>Please select a salon</option>";
                        for (var i = 0; i < response.length; i++) {
                            options += '<option value="' + response[i].Id +'">' + response[i].Name + '</option>';
                        }

                        $('#salonDDL').append(options);
                    } 
                },
                fail: function (error) {
                    alert(error.StatusText);
                }
            });

The controller is a different one and the method is defined thus: (the HttpPost is defined as being from the System.Web.Http namespace)

        [HttpPost]
        public IHttpActionResult GetSalonsByOrg([FromBody]GetSalonsByOrgParams passedParams)
        {
            List<Salon> salons = new List<Salon>();
            salons = _SalonService.GetSalonsByOrg(passedParams.id);

            try
            {
                if (passedParams.filter != null)
                {
                    return Json(salons.AsEnumerable().Where(s => s.City.ToLower().Contains(passedParams.filter.ToLower())).Select(s => new { Id = s.ID, Name = s.Name }).OrderBy(s => s.Name).ToList());
                }
                else
                {
                    return Json(salons.Select(s => new { Id = s.ID, Name = s.Name }).OrderBy(s => s.Name));
                }
            }
            catch (Exception ex)
            {
                _loggingService.LogError(ex, "Error in GetSalonsByOrg with filter of:" + passedParams.filter);
                return null;
            }
        }

Anything I'm missing here? I've been so close to this problem for a day now that I'm sure it's something simple so fresh eyes would be appreciated as I'm sole developer in the office! Many thanks for any advice.

Actually, this is not POST method. Do you have more methods in this controller?

OK. This isn't exactly an answer but hopefully my procedure to get it working might help someone. So I deleted the Web Service project and started again. Added a new project Asp.Net Web Application API. This automatically sets up a WebApiConfig.cs file in your App_Start folder. The route didn't work as it was set to routeTemplate: "api/{controller}/{id}", so I set it to routeTemplate: "api/{controller}/{action}/{id}",

You also get a ValuesController set up. Once the routing was changed, this then worked with the default GET and POST methods.

Next I added my GetServicesForSalon method. It still had the DefaultParams being passed in [FromBody] but instead of having int id {get;set;} declared I changed it to a string, eg string id {get;set;}

Hey presto, it worked.

I have just set up another controller(ServiceController) and copied the code into that to see what would happen. Identical apart from the name(obviously). It doesn't work. So https://localhost/OLBWebService/api/Values/GetServicesForSalon works. But. https://localhost/OLBWebService/api/Service/GetServicesForSalon doesn't work?

So it would seem you are limited to 1 controller which inherits the ApiController. No idea why this is but I now have multiple GET and POST methods working in the ValuesController which was set up by VS when I added the project.

Not ideal as I like to split out my methods according to objects, eg salon, staff, service, etc. But after wasting a day on this I'm just wanting to move on and make up some ground on lost time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM