skip to Main Content

I’m struggling to have the API PUT method working correctly while consuming my api (hosted on Plesk) from a blazor webassembly (.net6).

I Already have the GET and POST method working fine and already set my cors policy (AllowAnyOrigins,AllowAnyMethod,AllowAnyHeader) but still getting the error: "No 'Access-Control-Allow-Origin' header is present on the requested resource" and 405 if i try directly in the web api (swagger).
Any ideas?

here is the reply from swagger:

allow: GET,HEAD,OPTIONS,TRACE,PUT,POST content-length:
104 content-type: text/html date: Thu,05 May 2022 12:29:43 GMT
server: Microsoft-IIS/10.0 via: Proxy x-firefox-spdy: h2 x-powered-by: ASP.NET x-powered-by-plesk: PleskWin

request url

https://************.it/api/Requisitions/62

here is the controller:

[HttpPut("{id}")]  

    

public async Task<IActionResult> UpdateRequisitionAsync(int id, [FromBody] RequisitionDTO requisitionFromUI)
            {
                if (!ModelState.IsValid)
                {
                    throw new BadHttpRequestException("Error in the requisition");
                }
                else
                {
                    var requisitionInDb = await _context.Requisitions.SingleOrDefaultAsync(a => a.Id == requisitionFromUI.Id);
                    if (requisitionInDb != null)
                    {
                        requisitionInDb.PriceCurr = requisitionFromUI.PriceCurr;
                        requisitionInDb.PurchaseQty = requisitionFromUI.PurchaseQty;
                        requisitionInDb.WantedReceiptDate = requisitionFromUI.WantedReceiptDate;
                        requisitionInDb.PartDescription = requisitionFromUI.PartDescription;
                        requisitionInDb.RequisitionNote = requisitionFromUI.RequisitionNote;
                        await _context.SaveChangesAsync();
                    return Ok(requisitionFromUI);
                    }
                    return NotFound();
                }
            }

in program.cs:

builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
    builder.AllowAnyMethod().AllowAnyOrigin().AllowAnyHeader();
}));

var app = builder.Build();

the request pipeline:

app.UseSwagger();

if (!app.Environment.IsDevelopment())
{
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "myapi v1");
        c.RoutePrefix = String.Empty;
    });
}
else
{
    app.UseSwaggerUI(c => {});
}

app.UseHttpsRedirection();

app.UseCors("MyPolicy");

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

2

Answers


  1. Chosen as BEST ANSWER

    I was able to do it amending the web.config file as follow:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <location path="." inheritInChildApplications="false">
        <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
               <remove name="WebDAVModule" />
            </modules>
          <handlers>
            <add name="aspNetCore" path="*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
          </handlers>
          <aspNetCore processPath="dotnet" arguments=".RocketstarWebApiNext.dll" stdoutLogEnabled="false" stdoutLogFile=".logsstdout" hostingModel="inprocess" />
        </system.webServer>
      </location>
    </configuration>
    

    bu I'd like to have Visual Studio generating the file correctly and not fixing this every API publish/modifications.


  2. I am not sure, but here goes what I think could help you. You need to add allowed list of headers to your reponse in your API’s startup:

    app.Use(async (context, next) =>
    {
        context.Response.Headers.Add("Access-Control-Allow-Headers","Content-Type, Accept, Request-Language, Request-Timezone");
    });
    

    Also, you need to specify origins you allow using the Access-Control-Allow-Origin. Either only the origin is allowed, or another domain can be allowed or any origin.

    context.Response.Headers.Add("Access-Control-Allow-Origin", originHeader);
    

    Where context is your HttpContext. In the error message, or information message you get when your request is rejected because of preflight, it should tell you what header is not allowed.

    Read here Cross-Origin Resource Sharing

    Also read here about Middleware delegates

    browsers make a "preflight" request to the server hosting the
    cross-origin resource, in order to check that the server will permit
    the actual request. In that preflight, the browser sends headers that
    indicate the HTTP method and headers that will be used in the actual
    request.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search