How to enable CORS (Cross-Origin Requests)

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
9 年 前
I want to make an ajax call for specified address,
I add this code above my function, doesn't work

[EnableCors(origins: "*", headers: "*", methods: "*")]
public ActionResult myfunction()
{
}

thanks in advance
3 年 前
Please help
3 年 前
According to this document - https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors - it cannot be set by default;

Problem is sequence of registered middlewares;
1) "With endpoint routing, the CORS middleware must be configured to execute between the calls to UseRouting and UseEndpoints"
2)  " The call to UseCors must be placed after UseRouting, but before UseAuthorization"

By default NopCommerce first calls UseAuthorization and last UseRouting
3 年 前
rafal_zabrowarny wrote:

By default NopCommerce first calls UseAuthorization and last UseRouting


There is a work item related with this.
3 年 前
Hi
You could add new NopStartup with order greater than NopMvcStartup value like below code.


using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Nop.Core.Infrastructure;

namespace Nop.Web.Infrastructure
{
    public class CorsPolicyStartup : INopStartup
    {
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddCors(feature =>
                feature.AddPolicy(
                    "CorsPolicy",
                    apiPolicy => apiPolicy
                        .AllowAnyOrigin()
                        //.WithOrigins("http://localhost:4200")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .SetIsOriginAllowed(host => true)
                        //.AllowCredentials()
                ));
        }

        public void Configure(IApplicationBuilder application)
        {
            application.UseCors("CorsPolicy");
        }

        public int Order => 1001; //CorsPolicy should be after MVC
    }
}


Then you could apply
[EnableCors("CorsPolicy")] 
attribute for yours whole Controller or specific action method.

I tested it for Nop4.20 and works as well.

Hope this can be helpful.

With best regards.
M.Hajinezhad
Developer from nopForest team.
3 年 前
rafal_zabrowarny wrote:
By default NopCommerce first calls UseAuthorization and last UseRouting


Done. Please see this commit.
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.