0

I'm building REST Web Service using c#.

The I have a web application that is installed in another server. If I try to call any of these web services, I get this error

Access to XMLHttpRequest at 'https://test.domain.com/WS/Hab-Dem/Tar/api/Login' from origin 'https://std.apps.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

I have created this file:

public class PreflightRequestsHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
        {
            var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };

            // Define and add values to variables: origins, headers, methods (can be global) 
            response.Headers.Add("Access-Control-Allow-Origin", "*");
            response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
            response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.Headers.Add("Access-Control-Request-Headers", "*");

            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            tsc.SetResult(response);

            return tsc.Task;
        }

        return base.SendAsync(request, cancellationToken);
    }
}

In WebApiConfig.cs I have inserted this code:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    config.EnableCors(new EnableCorsAttribute("*", "*", "*", "X-Custom-Header"));
    config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional } );

    var jsonConfig = config.Formatters.JsonFormatter;
    jsonConfig.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
}

And in web.config file I have added this:

<system.webServer>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" 
             type="System.Web.Handlers.TransferRequestHandler" 
             preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

1 Answer 1

2
    // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', '*');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,X-Access-Token,XKey,Authorization');

//  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

https://www.digitalocean.com/community/questions/blocked-by-cors-policy-the-access-control-allow-origin-mean-stack

Sign up to request clarification or add additional context in comments.

5 Comments

In PreflightRequestsHandler class.
set Access-Control-Allow-Origin: test.domain.com/WS/Hab-Dem/Tar/api/Login
I don't have res.setHeader method.
I'm try to set your code in my PreflightRequestesHandler class but the error is the same
response.Headers.Add('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,X-Access-Token,XKey,Authorization'); response.Headers.Add('Access-Control-Allow-Origin','std.apps.com'); Can you please try with above 2 lines?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.