⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Cors Policy in .Net Core Web Api - Adding Support for C#

To add support for CorsPolicy in a .NET Core application, open the Startup.cs file and modify the ConfigureServices and Configure methods, as follows:

ConfigureServices

public void ConfigureServices(IServiceCollection services)
        {
            // Добавляем CorsPolicy
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
            
            
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }


Configure



        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            // Включаем использование CorsPolicy
            app.UseCors("CorsPolicy");


            app.UseHttpsRedirection();
            app.UseMvc();
        }



To enable CorsPolicy support for a specific method, add the following to the controller:

using Microsoft.AspNetCore.Cors;



And next to the controller method, specify the attribute:

[EnableCors("CorsPolicy")]



This will look something like this:

namespace ServerAPI.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        [HttpGet]
        [EnableCors("CorsPolicy")]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "API Merchant Started!" };
        }
...

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.