dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.58k stars 10.06k forks source link

Minimal API broke CORS middleware #34723

Closed sps014 closed 3 years ago

sps014 commented 3 years ago

On Dotnet 6 preview 6, CORS Middleware in Minimal API does not work even with correct configuration , keeps throwing CORS error on client side.

Here is my code

using Microsoft.AspNetCore.Builder;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using System.Web;
using System.IO;
using Microsoft.AspNetCore.Cors;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("https://localhost:5001",
                                              "https://localhost:5000",
                                              "https://mysite.netlify.app").
                                              AllowAnyMethod()
                                              .AllowAnyHeader();
                      });
});

builder.Services.AddResponseCaching();
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Saavn", Description = "Docs for my API", Version = "v1" });
});

var app = builder.Build();

HttpClient client = new HttpClient();

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

app.UseRouting();

//app.UseResponseCaching();
app.UseCors(MyAllowSpecificOrigins);

app.MapGet("/",()=> "(running)");
app.MapGet("/top", TopSearch);
app.MapGet("/search/{query}",Search);
app.MapGet("/info/{id}", Info);
app.MapGet("/album/{id}", Album);
app.MapGet("/playlist/{id}", Playlist);
app.MapGet("/lyrics/{id}", Lyrics);

await app.StartAsync();

async Task<string> Search(string query)
{

    if (string.IsNullOrWhiteSpace(query))
    {
        return string.Empty;
    }
    query=Uri.EscapeDataString(query);

    return await Query(Endpoints.SearchBaseUrl + query);
}
async Task<string> Info(string id)
{
    if (string.IsNullOrWhiteSpace(id))
        return string.Empty;

    return await Query(Endpoints.SongDetailUrl + id);
}
async Task<string> Album(string id)
{
    if (string.IsNullOrWhiteSpace(id))
        return string.Empty;

    return await Query(Endpoints.AlbumDetailUrl + id);
}
async Task<string> Lyrics(string id)
{
    if (string.IsNullOrWhiteSpace(id))
        return string.Empty;

    return await Query(Endpoints.LyricsUrl + id);
}

async Task<string> Playlist(string id)
{
    if (string.IsNullOrWhiteSpace(id))
        return string.Empty;

    var v = await Query(Endpoints.PlaylistDetailUrl + id);
    return v;
}

async Task<string> TopSearch()
{
    return await Query(Endpoints.TopChartsUrl);
}

async Task<string> Query(string url)
{
    var r = await client.GetAsync(url);
    return  await r.Content.ReadAsStringAsync();
}

record Cipher(string Key);
pranavkm commented 3 years ago

Inside of UseRouting the CORS middleware looks for CORS enabling metadata on an endpoint to determine if it needs to respond. In an MVC action, this is enabled by the presence of the EnableCorsAttribute. In a minimal action, you'd have to use RequireCors to enable it. Alternatively, you could configure the middleware before the call to UseRouting which should enable it for all requests indiscriminately.

sps014 commented 3 years ago

Is there a sample available also Can we expect documentation on same in future? Thanks

pranavkm commented 3 years ago

Something like this would work:

app.MapGet("/",()=> "(running)").RequireCors("_myAllowSpecificOrigins");

Can we expect documentation on same in future?

Yes, we're a bit behind on the docs while we're working on landing the minimal API feature work, but we do plan to get this resolved soon.

sps014 commented 3 years ago

Thanks for quick response

ghost commented 3 years ago

This issue has been resolved and has not had any activity for 1 day. It will be closed for housekeeping purposes.

See our Issue Management Policies for more information.