簡體   English   中英

在ASP.NET 5和MVC 6中啟用跨域請求(CORS)

[英]Enable cross-origin requests (CORS) in ASP.NET 5 & MVC 6

我試圖在我的MVC 6 WebApi項目中啟用CORS,但我發現了這個問題,重點是同樣的問題: 如何在ASP.NET 5和MVC 6中啟用跨域請求(CORS)?

看起來和我想做的完全一樣,但是當我進入這一部分時,就會遇到麻煩。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    //Add Cors support to the service
    services.AddCors();

    var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();

    policy.Headers.Add("*");    
    policy.Methods.Add("*");          
    policy.Origins.Add("*");
    policy.SupportsCredentials = true;

    services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment  env)
{
    // Configure the HTTP request pipeline.

    app.UseStaticFiles();
    //Use the new policy globally
    app.UseCors("mypolicy");
    // Add MVC to the request pipeline.
    app.UseMvc();
}

它(以及我發現的與此主題有關的任何其他資源)都明確指出,我應該在Startup.cs -file的Configure方法中使用app.UseCors("policyname") 但是當我這樣做時,出現以下錯誤:

'IApplicationBuilder' does not contain a definition for 'UseCors' and no extension method 'UseCors' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)

我知道這是MVC 6中的全新功能,也許可以解釋為什么我無法找到有關如何實現此功能的任何官方文檔。

就像添加正確的NuGet包一樣簡單嗎? 我已經嘗試了來自Microsoft的幾個與CORS相關的.Net NuGet軟件包,但它們沒有解決問題,我懷疑它們與舊版本的WebApi有關。

加上這個

using Microsoft.AspNet.Builder;

並確保您的project.json文件中有包

Microsoft.AspNet.Cors.Core

這是擴展程序的圖像

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM