简体   繁体   English

MVC和Web Api:请求的资源不支持http方法“ POST”

[英]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. 我在Visual Studio 2019中有一个包含多个MVC项目的解决方案。 I want to add a Web Service which I have duly done. 我想添加一个我已经正确完成的Web服务。 All good so far. 到目前为止一切都很好。 So I have a call being made to this Web Service using ajax, thus: 因此,我使用ajax对此Web服务进行了调用,因此:

            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: 我目前在WebApiConfig.cs中具有路由,因此:

            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被定义为来自System.Web.Http命名空间)

        [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: 这样定义了传入的DefaultParam:

    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'". 当我通过Visual Studio 2019调试模式或使用Fiddler运行它时,我收到消息``请求的资源不支持http方法'POST'''。

The strange thing is I have an ajax call prior to this one which works. 奇怪的是,在此有效之前,我有一个ajax调用。 (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定义为来自System.Web.Http命名空间)

        [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. 实际上,这不是POST方法。 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. 因此,我删除了Web Service项目并重新开始。 Added a new project Asp.Net Web Application API. 添加了一个新的项目Asp.Net Web应用程序API。 This automatically sets up a WebApiConfig.cs file in your App_Start folder. 这将在您的App_Start文件夹中自动设置一个WebApiConfig.cs文件。 The route didn't work as it was set to routeTemplate: "api/{controller}/{id}", so I set it to routeTemplate: "api/{controller}/{action}/{id}", 路由由于设置为routeTemplate:“ api / {controller} / {id}”而无法正常工作,因此我将其设置为routeTemplate:“ api / {controller} / {action} / {id}”,

You also get a ValuesController set up. 您还将获得一个ValuesController设置。 Once the routing was changed, this then worked with the default GET and POST methods. 一旦更改了路由,便可以使用默认的GET和POST方法。

Next I added my GetServicesForSalon method. 接下来,我添加了我的GetServicesForSalon方法。 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;} 它仍然具有在[FromBody]中传递的DefaultParams,但是没有声明int id {get; set;},而是将其更改为字符串,例如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. 我刚刚设置了另一个控制器(ServiceController),并将代码复制到其中,以查看会发生什么。 Identical apart from the name(obviously). 与名称相同(显然)。 It doesn't work. 没用 So https://localhost/OLBWebService/api/Values/GetServicesForSalon works. 所以https:// localhost / OLBWebService / api / Values / GetServicesForSalon可以工作。 But. 但。 https://localhost/OLBWebService/api/Service/GetServicesForSalon doesn't work? https:// localhost / OLBWebService / api / Service / GetServicesForSalon不起作用?

So it would seem you are limited to 1 controller which inherits the ApiController. 因此,似乎您仅限于1个继承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. 不知道为什么会这样,但是我现在有多个GET和POST方法在ValuesController中工作,这是我在添加项目时由VS设置的。

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. 由于我想根据对象(例如沙龙,员工,服务等)来划分我的方法,所以这不是理想的方法。但是在浪费了一天的时间之后,我只是想继续前进,并在浪费的时间上有所作为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Web API - 405 - 请求的资源不支持http方法&#39;PUT&#39; - Web API - 405 - The requested resource does not support http method 'PUT' ASP.NET Web API:“消息”:“请求的资源不支持 http 方法 &#39;POST&#39;、PUT、DELETE。” 在邮递员 - ASP.NET Web API: "Message": "The requested resource does not support http method 'POST', PUT, DELETE." in Postman 请求的资源不支持 http 方法“GET”,但使用“POST” - The requested resource does not support http method 'GET' but using 'POST' 如何修复 - 请求的资源不支持 http 方法“POST” - How to fix - The requested resource does not support http method 'POST' “消息”:“请求的资源不支持http方法&#39;POST&#39;。” .net api中的JSON返回 - “Message”: “The requested resource does not support http method 'POST'.” JSON return in .net api api发布错误:请求的资源不支持http方法&#39;GET&#39;.88 - Api Post error:The requested resource does not support http method 'GET'.88 Asp.net Web api请求的资源不支持http方法&#39;GET&#39; - Asp.net Web api The requested resource does not support http method 'GET' ASP.NET Web Api“请求的资源不支持http方法PUT / DELETE” - ASP.NET Web Api “The requested resource does not support http method PUT/DELETE” ASP.NET Web API - 请求的资源不支持 Z80791B3AE7002CB88C246876D9FA 方法 - ASP.NET Web API - The requested resource does not support http method 'GET' “请求的资源不支持HTTP方法&#39;PUT&#39;ASP.Net Web API - "The requested resource does not support HTTP method 'PUT' ASP.Net Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM