S
S
Stazhor2020-09-14 14:01:58
ASP.NET
Stazhor, 2020-09-14 14:01:58

Why does CORS restrict access to the POST action?

Hello. There is a WEB API service on .net core 2.1, which has the action of saving the model from the form:

[HttpPost("[action]")]
public async Task<IActionResult> Save([FromForm] Document document)
    {
       //Некоторые действия.
    }


There is also a .net core mvc client application. js sends the data from the form to the web api. The code:

function SubmitForm(formData) {
    let xhr = new XMLHttpRequest();
    let form = new FormData(formData);
    xhr.open('POST', 'http://localhost:57803/api/save');
    xhr.onload = () => {
        if (xhr.status == 200) {
            alert('Все норм!');
        }
        else {
            alert('Произошла ошибка!');
        }
    };
    xhr.send(form);
};


But when sending this request, an error occurs in the console: Access to XMLHttpRequest at ' localhost:57803/api/save ' from origin ' https://localhost:44377 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin ' header is present on the requested resource. Although the StartUp web api class indicated the following:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseCors(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); });
  
        app.UseMvc();
    }


It is also worth noting that there is a method for deleting an object in the WEB API:

[HttpDelete("[action]/{id}")]
    public async Task<IActionResult> Delete(int id)
    {
       //Некоторые действия.
    }


And in the client application the following code:

function deleteDoc(id, documentName) {
        let xhr = new XMLHttpRequest();
        xhr.open('DELETE', 'http://localhost:57803/api/delete/' + id);
        xhr.onload = () => {
            if (xhr.status == 200) {
                deleteRow(id, documentName);
            }
            else {
                errorDelete();   
            }
        };
        xhr.send();
    };


What is strange, the deletion works fine, but the post-request is blocked. I do not know where to dig, tell me, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yuopi, 2020-09-14
@yuopi

In ConfigureServices:

services.AddCors(options =>
            {
               options.AddPolicy("CorsPolicy", builder => builder
                    .SetIsOriginAllowed(e => true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

In configure:
app.UseCors("CorsPolicy");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question