不允许使用 REST API - 405 方法



我是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,它工作正常。但它无法从应用程序工作。

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

使用 Nuget 包下载

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

我认为问题是 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);
            }
        }
    }

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

最新更新