0

I've created an API and have the following within the WebApiConfig.cs:

var cors = new EnableCorsAttribute("http://localhost:3000", "*", "*");
config.EnableCors(cors);

I'm able to access it with my React application but I've created a new method within one of the controllers and restarted the API. When I tested it in Postman by sending a POST request it worked fine. However I'm now getting the error in the title when I try to access it using my React application. All other methods within the controller work fine. It's just this new one that is causing issues:

Accessing new method in React

        const requestOptions = {
            method: 'post',
            headers: { "Content-type":"application/json",
                       "Accept":"*/*",
                       "Accept-Encoding":"gzip, deflate, br" },
            body: JSON.stringify({ Data: this.props.data})
        };
        fetch("http://localhost:9074/Output/EditByMultipleIDs?varA=" + this.state.varA + "&varB=" + this.state.varB + "&varC=" + this.state.varC, requestOptions)
            .then(response => response.json());

varA and varC are just a string of comma separated ids and varB is just an integer.

One which works from the same controller

        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ Data:this.props.data})
        };
        fetch("http://localhost:9074/Output/EditByID?varA=" + this.state.varA + "&varB=" + this.state.varB, requestOptions)
             .then(response => response.json());

here varA and varB are just integers.

I had tried to add in extra headers but that didn't seem to have worked and had also tried to add in [EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")] into the controller but that didn't help either.

I've noticed that if I remove [System.Web.Mvc.HttpPost] from the EditByMultipleIDs method within the controller then I'm able to hit the method without any CORS issue but then my model variable is null as nothing is passed into it from the body.

Below are the declaration for both methods within the controller:

[System.Web.Mvc.HttpPost]
        public ActionResult EditByMultipleIDs(string varA, [FromBody] DTO model, int varB, string varC)
        { //... Do stuff}

[System.Web.Mvc.HttpPost]
        public ActionResult EditByID(int varA, [FromBody] DTO model, int varB)
        {//... Do stuff}

Also when I open the link in chrome I get:

error in chrome

I'm not sure if that's because the body data is lost so it's not able to complete the request or what but yeah...

EDIT 1: Actual Requests being made:

General

Request URL: http://localhost:9074/Output/EditByMultipleIDs?varA=55279,55280&varB=3&varC=393,394
Request Method: OPTIONS
Status Code: 404 Not Found
Remote Address: [::1]:9074
Referrer Policy: strict-origin-when-cross-origin

Response Headers

Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Cache-Control: private
Content-Length: 4500
Content-Type: text/html; charset=utf-8
Date: Mon, 04 Jul 2022 08:59:48 GMT
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcbW5hemlyXERlc2t0b3BcQWZ0b25cUnVsZXMgRW5naW5lXFJ1bGVFbmdpbmVBUEkgLSBDb3B5XFJ1bGVFbmdpbmVBUElcT3V0cHV0XEVkaXRCeU11bHRpcGxlSURz?=

Request Headers

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:9074
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
Manib
  • 171
  • 15
  • Does this answer your question? [Why does my http://localhost CORS origin not work?](https://stackoverflow.com/questions/10883211/why-does-my-http-localhost-cors-origin-not-work) – Alan Jun 30 '22 at 22:56
  • This is a duplicate and has been asked several times. All browsers disallow CORS for localhost. POSTMAN is not a browser, so it will work. The 404 error you are getting is your App not finding whatever URL you are calling. The proper work around is to not use localhost when accessing your app locally. A terrible solution is to disable websecurity in your browser. – Alan Jun 30 '22 at 22:59
  • What I don't understand is that why is it that it works for all the other controllers/methods but doesn't work for the new method I had put into the controller? – Manib Jul 01 '22 at 08:21
  • in one of your examples (it's not clear if that is the route that isn't working), you set the `request.method` to `post` and it should be `POST`. So I assume `window.fetch` is falling back making a `GET`, and your controller doesn't define a `GET` handler for that route, you would get a 404. There is not enough debug information for me to tell, but I reocmmend opening up your browser developer console and check what the actual request that is being made. – Alan Jul 01 '22 at 20:27
  • I've added in the request info. Seems like it's sending a POST request in the request headers but says OPTIONS in the general section which is being rejected because of CORS policy but I don't see why that is. – Manib Jul 05 '22 at 14:40
  • `OPTIONS` is sent via the browser as a pre-flight check for CORS (see more here: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request) It's likely your IIS configuration needs to be updated to allow `OPTIONS` https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors – Alan Jul 05 '22 at 17:41
  • It should be enabled via the settings I've applied within WebAPIConfig.cs: var cors = new EnableCorsAttribute("http://localhost:3000", "*", "*"); config.EnableCors(cors); – Manib Jul 06 '22 at 10:23
  • I had found the solution here: https://stackoverflow.com/questions/13624386/handling-cors-preflight-requests-to-asp-net-mvc-actions – Manib Jul 06 '22 at 10:38

1 Answers1

0

I had found the solution here: Handling CORS Preflight requests to ASP.NET MVC actions

Just need to add in:

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) &&
        Request.HttpMethod == "OPTIONS") {
        Response.Flush();
    }
}

into Global.asax file so that it sends an empty response whenever it gets a OPTIONS request

Manib
  • 171
  • 15