Rest API - 405方法不允许

时间:2017-01-12 12:30:17

标签: ajax rest model-view-controller asp.net-web-api wcf-rest

我是Rest API的新手。我试图从我的应用程序调用跨域rest API。 这是我的代码 -

 $.ajax({
            type: "GET",
            async: false,
            url: 'http://xx.xxx.xxx.xx:9003/GetProjectList',
            contentType: "application/json",
            dataType: "json",
            traditional: true,
            CrossDomain: true,
            data: {
                StartDate: '2016-12-20',
                EndDate: '2017-01-10'
            },
            success: function (data) {
                alert("Success");
                alert(data);

            },

            error: function (xhr, textStatus, errorThrown) {
                alert("Failed");
                alert(xhr);
                alert(textStatus);
                alert(errorThrown);

            }
        }); 

但我收到的错误是

OPTIONS http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10 405 (Method Not Allowed)

XMLHttpRequest cannot load http://xx.xxx.xxx.xx:9003/GetProjectList?StartDate=2016-12-20&EndDate=2017-01-10. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64207' is therefore not allowed access. The response had HTTP status code 405.

我在这里遗漏了什么?任何代码或配置?

如果我直接从浏览器或邮递员点击该URL,它的工作正常。但它不适用于应用程序。

2 个答案:

答案 0 :(得分:2)

问题在于CORS(跨域请求)。您必须启用CORS才能解决问题。

使用Nuget Package下载

Install-Package Microsoft.AspNet.WebApi.Cors

您应该在WebApiConfig.cs中添加一些代码

var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);

您应该查看更多信息: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

答案 1 :(得分:0)

我认为这个问题是一个CORS问题(有时候405也意味着你用错误的HTTP动词调用你的API)..但是阅读你的异常它看起来像一个CORS问题..试试这个:

using Goocity.API;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup("API", typeof(Goocity.API.Startup))]

    namespace Goocity.API
    {
        public partial class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                #region TO UNCOMMENT WHEN IS IN PRODUCTION
                //var corsPolicy = new CorsPolicy
                //{
                //    AllowAnyMethod = true,
                //    AllowAnyHeader = true,
                //    SupportsCredentials = true,
                //    Origins = { "http://www.yoursite.it" }
                //};

                //app.UseCors(new CorsOptions
                //{
                //    PolicyProvider = new CorsPolicyProvider
                //    {
                //        PolicyResolver = context => Task.FromResult(corsPolicy)
                //    }
                //});
                #endregion TO UNCOMMENT WHEN IS IN PRODUCTION

                app.UseCors(CorsOptions.AllowAll);
                ConfigureAuth(app);

            }
        }
    }

尝试将其放入startUp文件并安装Microsoft.Owin.Cors nuget包