简体   繁体   English

MVC web api:请求的资源上不存在“Access-Control-Allow-Origin”标头

[英]MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I tried everything that is written in this article: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api , but nothing works.我尝试了本文中写的所有内容: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api ,但没有任何效果。 I'm trying to get data from webAPI2 (MVC5) to use in another domain using angularJS.我正在尝试从 webAPI2 (MVC5) 获取数据以使用 angularJS 在另一个域中使用。

my controller looks like this:我的控制器看起来像这样:

namespace tapuzWebAPI.Controllers
{
    [EnableCors(origins: "http://local.tapuz.co.il", headers: "*", methods: "*", SupportsCredentials = true)]
    [RoutePrefix("api/homepage")]
    public class HomePageController : ApiController
    {
        [HttpGet]
        [Route("GetMainItems")]
        //[ResponseType(typeof(Product))]
        public List<usp_MobileSelectTopSecondaryItemsByCategoryResult> GetMainItems()
        {


            HomePageDALcs dal = new HomePageDALcs();
            //Three product added to display the data

            //HomePagePromotedItems.Value.Add(new HomePagePromotedItem.Value.FirstOrDefault((p) => p.ID == id));


            List<usp_MobileSelectTopSecondaryItemsByCategoryResult> items = dal.MobileSelectTopSecondaryItemsByCategory(3, 5);
            return items;

        }      
    }
}

You need to enable CORS in your Web Api .您需要在Web Api 中启用CORS The easier and preferred way to enable CORS globally is to add the following into web.config全局启用 CORS 的更简单和首选的方法是将以下内容添加到web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Please note that the Methods are all individually specified, instead of using * .请注意,方法都是单独指定的,而不是使用* This is because there is a bug occurring when using * .这是因为在使用*时发生了错误。

You can also enable CORS by code.您还可以通过代码启用CORS

Update更新
The following NuGet package is required: Microsoft.AspNet.WebApi.Cors .需要以下NuGet包: Microsoft.AspNet.WebApi.Cors

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        // ...
    }
}

Then you can use the [EnableCors] attribute on Actions or Controllers like this然后你可以像这样在动作或控制器上使用[EnableCors]属性

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]

Or you can register it globally或者你可以全局注册

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
        config.EnableCors(cors);

        // ...
    }
}

You also need to handle the preflight Options requests with HTTP OPTIONS requests.您还需要办理预检Options请求HTTP OPTIONS请求。

Web API needs to respond to the Options request in order to confirm that it is indeed configured to support CORS . Web API需要响应Options请求,以确认它确实配置为支持CORS

To handle this, all you need to do is send an empty response back.要处理这个问题,您需要做的就是发回一个空响应 You can do this inside your actions, or you can do it globally like this:您可以在您的操作中执行此操作,也可以像这样全局执行此操作:

# Global.asax.cs
protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

This extra check was added to ensure that old APIs that were designed to accept only GET and POST requests will not be exploited.添加此额外检查是为了确保设计为仅接受GETPOST请求的旧APIs不会被利用。 Imagine sending a DELETE request to an API designed when this verb didn't exist.想象一下,当这个动词不存在时,向一个设计的API发送一个DELETE请求。 The outcome is unpredictable and the results might be dangerous .结果是不可预测的,结果可能是危险的

@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error. @Mihai-Andrei Dinculescu 的回答是正确的,但为了搜索者的利益,还有一个微妙的地方可能会导致此错误。

Adding a '/' on the end of your URL will stop EnableCors from working in all instances (eg from the homepage).在 URL 末尾添加“/”将阻止 EnableCors 在所有情况下(例如从主页)工作。

Ie This will not work即这行不通

var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);

but this will work:但这会起作用:

var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);

The effect is the same if using the EnableCors Attribute.如果使用 EnableCors 属性,效果相同。

I followed all the steps above indicated by Mihai-Andrei Dinculescu .我遵循了Mihai-Andrei Dinculescu指出的所有步骤。
But in my case, I needed 1 more step because http OPTIONS was disabled in the Web.Config by the line below.但就我而言,我还需要1 个步骤,因为 http OPTIONS 在 Web.Config 中被以下行禁用。

<remove name="OPTIONSVerbHandler" />

I just removed it from Web.Config (just comment it like below) and Cors works like a charm我刚刚从 Web.Config 中删除了它(只需像下面一样评论它),Cors 就像一个魅力

<handlers>
  <!-- remove name="OPTIONSVerbHandler" / -->
</handlers>

It may be because of the installation of Cors nuget packages.可能是因为安装了 Cors nuget 包。

If you facing the problem after installing and enabaling cors from nuget , then you may try reinstalling web Api.如果您在从 nuget 安装和启用 cors 后遇到问题,那么您可以尝试重新安装 web Api。

From the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall在包管理器中,运行Update-Package Microsoft.AspNet.WebApi -reinstall

Try this, to make sure you configured CORS correctly:试试这个,以确保你正确配置了 CORS:

[EnableCors(origins: "*", headers: "*", methods: "*")]

Still not working?还是行不通? Check HTTP headers presence.检查 HTTP 标头是否存在。

I know I'm coming to this very late.我知道我来得很晚。 However, for anyone who's searching, I thought I'd publish what FINALLY worked for me.但是,对于正在搜索的任何人,我想我会发布最终对我有用的内容。 I'm not claiming it's the best solution - only that it worked.我并不是说这是最好的解决方案——只是说它有效。

Our WebApi service uses the config.EnableCors(corsAttribute) method.我们的 WebApi 服务使用 config.EnableCors(corsAttribute) 方法。 However, even with that, it would still fail on the pre-flight requests.然而,即便如此,它仍然会在飞行前请求上失败。 @Mihai-Andrei Dinculescu's answer provided the clue for me. @Mihai-Andrei Dinculescu 的回答为我提供了线索。 First of all, I added his Application_BeginRequest() code to flush the options requests.首先,我添加了他的 Application_BeginRequest() 代码来刷新选项请求。 That STILL didn't work for me.那仍然对我不起作用。 The issue is that WebAPI still wasn't adding any of the expected headers to the OPTIONS request.问题是 WebAPI 仍然没有向 OPTIONS 请求添加任何预期的标头。 Flushing it alone didn't work - but it gave me an idea.单独冲洗它没有用 - 但它给了我一个想法。 I added the custom headers that would otherwise be added via the web.config to the response for the OPTIONS request.我添加了自定义标头,否则这些标头将通过 web.config 添加到 OPTIONS 请求的响应中。 Here's my code:这是我的代码:

protected void Application_BeginRequest()
{
  if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
  {
    Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44343");
    Response.Headers.Add("Access-Control-Allow-Headers",
      "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    Response.Flush();
  }
}

Obviously, this only applies to the OPTIONS requests.显然,这仅适用于 OPTIONS 请求。 All other verbs are handled by the CORS configuration.所有其他动词都由 CORS 配置处理。 If there's a better approach to this, I'm all ears.如果有更好的方法来解决这个问题,我会全力以赴。 It feels like a cheat to me and I would prefer if the headers were added automatically, but this is what finally worked and allowed me to move on.对我来说这感觉像是作弊,我更喜欢自动添加标题,但这最终奏效并让我继续前进。

To make any CORS protocol to work, you need to have a OPTIONS method on every endpoint (or a global filter with this method) that will return those headers :要使任何 CORS 协议工作,您需要在每个端点(或具有此方法的全局过滤器)上都有一个 OPTIONS 方法,该方法将返回这些标头:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: content-type

The reason is that the browser will send first an OPTIONS request to 'test' your server and see the authorizations原因是浏览器将首先发送一个 OPTIONS 请求来“测试”您的服务器并查看授权

I catch the next case about cors.我抓住了关于 cors 的下一个案例。 Maybe it will be useful to somebody.也许这对某人有用。 If you add feature 'WebDav Redirector' to your server, PUT and DELETE requests are failed.如果您将功能“WebDav 重定向器”添加到您的服务器,PUT 和 DELETE 请求将失败。

So, you will need to remove 'WebDAVModule' from your IIS server:因此,您需要从 IIS 服务器中删除“WebDAVModule”:

  • "In the IIS modules Configuration, loop up the WebDAVModule, if your web server has it, then remove it". “在 IIS 模块配置中,循环 WebDAVModule,如果您的 Web 服务器有它,则将其删除”。

Or add to your config:或添加到您的配置:

<system.webServer>
<modules>
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="WebDAV" />
  ...
</handlers>

That problem happens when you try to access from a different domain or different port.当您尝试从不同的域或不同的端口访问时,就会发生该问题。

If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console.如果您使用的是 Visual Studio,请转到“工具”>“NuGet 包管理器”>“包管理器控制台”。 There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors在那里你必须安装 NuGet 包Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors

Then, in PROJECT > App_Start > WebApiConfig, enable CORS然后,在 PROJECT > App_Start > WebApiConfig 中,启用 CORS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        
        //Enable CORS. Note that the domain doesn't have / in the end.
        config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));

        ....

    }
}

Once installed successfully, build the solution and that should suffice成功安装后,构建解决方案就足够了

@Mihai-Andrei Dinculescu's answer worked for me, eg: @Mihai-Andrei Dinculescu 的回答对我有用,例如:

  • Adding a <httpProtocol> in the web.config's <system.webServer> section在 web.config 的<system.webServer>部分添加一个<httpProtocol>
  • Returning empty response for OPTIONS requests via the mentioned Application_BeginRequest() in global.asax通过global.asax提到的Application_BeginRequest()OPTIONS请求返回空响应

Except that his check for Request.Headers.AllKeys.Contains("Origin") did NOT work for me, because the request contained an origing , so with lowercase.除了他对Request.Headers.AllKeys.Contains("Origin")检查对我不起作用,因为请求包含origing ,所以使用小写。 I think my browser (Chrome) sends it like this for CORS requests.我认为我的浏览器(Chrome)会像这样为 CORS 请求发送它。

I solved this a bit more generically by using a case insensitive variant of his Contains check instead: if (culture.CompareInfo.IndexOf(string.Join(",", Request.Headers.AllKeys), "Origin", CompareOptions.IgnoreCase) >= 0) {我通过使用他的Contains检查的不区分大小写的变体来更通用地解决这个问题: if (culture.CompareInfo.IndexOf(string.Join(",", Request.Headers.AllKeys), "Origin", CompareOptions.IgnoreCase) >= 0) {

If you have security\\requestFiltering nodes in your web.config as follows:如果您的 web.config 中有 security\\requestFiltering 节点,如下所示:

<security>
  <requestFiltering>
    <verbs allowUnlisted="false">
      <add verb="GET" allowed="true" />
      <add verb="POST" allowed="true" />
      <add verb="PUT" allowed="true" />
      <add verb="DELETE" allowed="true" />
      <add verb="DEBUG" allowed="true" />          
    </verbs>
  </requestFiltering>

make sure you add this as well确保你也添加这个

<add verb="OPTIONS" allowed="true" />

I had tried everything I could find on the net including the methods that have been given on this answer.我已经尝试了所有可以在网上找到的方法,包括在这个答案中给出的方法。 After almost trying to solve the problem for whole day I have found the solution that have worked for me like a charm.在几乎尝试解决问题一整天之后,我找到了对我有用的解决方案。

in the file WebApiConfig in folder App_Start , comment all the lines of code and add the following code:在文件夹App_Start中的文件WebApiConfig中,注释所有代码行并添加以下代码:

`public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();
        var enableCorsAttribute = new EnableCorsAttribute("*",
                                           "Origin, Content-Type, Accept",
                                           "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
        // Web API routes
        config.MapHttpAttributeRoutes();

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

    public class BrowserJsonFormatter : JsonMediaTypeFormatter
    {
        public BrowserJsonFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            this.SerializerSettings.Formatting = Formatting.Indented;
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }`

I know that people will probably find this very obvious at first, but really think about this.我知道人们一开始可能会觉得这很明显,但仔细想想。 This can often happen if you've done something wrong.如果您做错了什么,这通常会发生。

For instance, I've had this problem because I didn't add a host entry to my hosts file.例如,我遇到了这个问题,因为我没有在我的主机文件中添加主机条目。 The real problem was DNS resolution.真正的问题是 DNS 解析。 Or I just got the base URL wrong.或者我只是把基本 URL 弄错了。

Sometimes I get this error if the identity token came from one server, but I'm trying to use it on another.如果身份令牌来自一台服务器,有时我会收到此错误,但我正在尝试在另一台服务器上使用它。

Sometimes you'll get this error if you've got the resource wrong.有时,如果您的资源有误,您会收到此错误。

You might get this if you put the CORS middleware too late in the chain.如果您将 CORS 中间件放入链中太晚,您可能会得到这个。

Avoid multiple place enabling CORS,Like WebApiCOnfig.cs, GrantResourceOwnerCredentials method in provider and Controller Header attribute etc. Below are the list which also cause the Access Control Allow Origin避免多处启用 CORS,如 WebApiCOnfig.cs、提供者中的 GrantResourceOwnerCredentials 方法和 Controller Header 属性等。以下是导致访问控制允许来源的列表

  1. Web having truble in interacting with DB which you used.与您使用的数据库交互的网络有问题。
  2. AWS Cloud If VPC of Web API and DB are different. AWS Cloud 如果 Web API 和 DB 的 VPC 不同。

Below code is more then enough to fix the access control allow origin.下面的代码足以修复访问控制允许来源。 //Make sure app.UseCors should be top of the code line of configuration. //确保 app.UseCors 应该是配置代码行的顶部。

   public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            //All other configurations
        }
    }

This slowed my problem.这减缓了我的问题。

Install package : Microsoft.AspNet.WebApi.Cors安装包:Microsoft.AspNet.WebApi.Cors

go to : App_Start --> WebApiConfig转到:App_Start --> WebApiConfig

Add :添加 :

var cors = new EnableCorsAttribute("http://localhost:4200", " ", " "); var cors = new EnableCorsAttribute("http://localhost:4200", " ", " "); config.EnableCors(cors); config.EnableCors(cors);

Note : If you add '/' as end of the particular url not worked for me.注意:如果您添加“/”作为特定 url 的结尾对我不起作用。

For people that are simply creating a Web API in .NET 5 and not a Web App, in Startup.cs you'll need to configure your policy like so:对于那些只是在 .NET 5 中创建 Web API 而不是 Web 应用程序的人,在Startup.cs您需要像这样配置您的策略:

public void ConfigureServices(IServiceCollection services)
{
    // Additional configs above...
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAnyOrigin", builder =>
        {
            // Allow "Access-Control-Allow-Origin: *" header
            builder.AllowAnyOrigin();
        });
    });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Add this above other config options...
    app.UseCors("AllowAnyOrigin");
}

I know this sounds crazy but for me it was [HttpPost()] instead of [HttpPost].我知道这听起来很疯狂,但对我来说是 [HttpPost()] 而不是 [HttpPost]。 When I removed the redundant parentheses, it started working当我删除多余的括号时,它开始工作

暂无
暂无

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

相关问题 Web API中的请求资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource in web api c#已启用CORS的Web Api和所请求资源上存在可怕的“Access-Control-Allow-Origin”标头 - c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource CORS所请求的资源上没有“ Access-Control-Allow-Origin”标头 - CORS No 'Access-Control-Allow-Origin' header is present on the requested resource CORS - 没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource 请求的资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource 问题:请求的资源上不存在“Access-Control-Allow-Origin”header - Issue: No 'Access-Control-Allow-Origin' header is present on the requested resource In.Net Core 2.1 Web API 用于 PUT 和 DELETE,仅为什么请求的资源上存在“No 'Access-Control-Allow-Origin' header” - In .Net Core 2.1 Web API for PUT and DELETE only why “No 'Access-Control-Allow-Origin' header is present on the requested resource” ASP.NET Web窗体:所请求的资源上不存在“ Access-Control-Allow-Origin”标头 - ASP.NET Web Forms: No 'Access-Control-Allow-Origin' header is present on the requested resource Azure 应用服务 API 中的“请求的资源上不存在‘访问控制允许来源’header” - "No 'Access-Control-Allow-Origin' header is present on the requested resource" from Azure App Service API 使用 http 访问 API 时,请求的资源错误中不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource error while accessing the API using http
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM