DoctorPrisme
DoctorPrisme

Reputation: 103

WEB API : I apparently can't enable CORS ( ? )

Ahoy Coder friends.

After this question Angular 2 + web api it came to my mind I might have to enable CORS for my front end to reach my back-end web api.

However, even if I tried these steps http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/08/31/how-to-enable-cors-in-the-asp-net-web-api.aspx as well as these https://enable-cors.org/server_aspnet.html , apparently nothing changed : when I try to reach http://localhost:58825/api/character with postman, I receive the list of characters expected, but there is no CORS header (allow-origin etc) in the answer. As for the frontend, you might see in the linked question that angular doesn't even find the API.

Here is the relevant sample of web.config :

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        var cors = new EnableCorsAttribute("http://localhost:3000", "*", "*");
        config.EnableCors(cors);

As well as the controller :

public class CharacterController : ApiController
{
    private readonly CharacterRepository repo = new CharacterRepository();
    JavaScriptSerializer jsonConverter = new JavaScriptSerializer();

    [EnableCors(origins:"http://localhost:3000", headers:"*", methods:"*")]
    // GET: api/Character
    public IEnumerable<string> GetAll()
    {
        List<Character> myCharacs = repo.Get().ToList();
        List<String> myJsonCharacs = new List<string>();
        foreach (var charac in myCharacs)
        {
            var cur = jsonConverter.Serialize(charac);
            myJsonCharacs.Add(cur);
        }

        return myJsonCharacs;
        //return myCharacs;
    }

Obviously, I added the nuget package Microsoft.AspNet.WebApi.Cors (5.2.2).

I tried cleaning the solution, rebuilding, restarting VS... I've look at the "similars question" asked here on SO, but I don't even have the "no headers" exception, my requests seem to pass without giving a f*ck about CORS.

My front end app is on localhost:3000, my api is on localhost:58225 (I start it via visual studio, if this changes anything)

Does anyone know what I'm miserably failing at? (except life, that's not a problem, I'm used to it)

Edit : possible doublon of Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

Re-Edit : I don't know if it's a true doublon, but I managed to solve my problem by adding

add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."  
verb="GET,HEAD,POST,PUT,DELETE"     
type="System.Web.Handlers.TransferRequestHandler"     
preCondition="integratedMode,runtimeVersionv4.0" /

to my webconfig file,as described in the original post,and I now see the headers in postman.

Upvotes: 1

Views: 570

Answers (1)

Lazov
Lazov

Reputation: 1476

When you need to enable CORS you can go to the Startup.cs file and add:

using Microsoft.Owin.Cors;

at the beginning. Then you have two options:

  1. You specify the origins:

    var corsPolicy = new CorsPolicy { AllowAnyHeader = true, AllowAnyMethod = true };
            corsPolicy.Origins.Add("your origin");
            var corsOptions = new CorsOptions
                        {
                            PolicyProvider = new CorsPolicyProvider
                            {
                                PolicyResolver = context => Task.FromResult(corsPolicy)
                            }
                        };
    
  2. You allow all of them:

    app.UseCors(CorsOptions.AllowAll);
    

Each of these happens in the Configuration method.

Upvotes: 1

Related Questions