ASP Net Core API- PUT方法

发布于 2025-01-26 08:53:19 字数 2505 浏览 4 评论 0原文

我正在努力使API PUT方法正常工作,同时消费了我的API(托管在Plesk)中,这是从Glazor WebAssembly(.NET6)中使用的。

我已经有get和post方法正常工作,并且已经设置了我的CORS策略(allowanyoriginsallowAnymethodallowaneheader),但仍会遇到错误: “如果我直接在Web API(Swagger)中尝试,则在请求的资源>和405上没有'访问控制 - 遵守孔“孔”标头。 有什么想法吗?

这是Swagger的答复:

允许:获取,头,选项,跟踪,put,发布内容长度: 104内容类型:文本/html日期:THU,2022年5月5日12:29:43 GMT
服务器:Microsoft-iis/10.0通过:代理X-FireFox-Spdy:H2 X-Power-By:Asp.net X-Powered-By-persek:Pleskwin

请求url url url

https:// ********* ***。it/api/requinisitions/62

这是控制器:

[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();

请求管道:

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();

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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌吟 2025-02-02 08:53:19

我不确定,但是我认为可以为您提供帮助。您需要在API的启动中添加允许的标头列表:

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

另外,您需要指定允许使用访问控制的起源。要么只允许原点,要么允许其他域或任何原点。

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

您的httpcontext是上下文。在错误消息或您的信息消息中,当您的请求因前飞行而被拒绝时收到的信息消息,它应该告诉您不允许什么标头。

cross-origin资源共享

在这里阅读 href =“ https://learn.microsoft.com/en-us/aspnet/core/core/fundamentals/middleware/?view = ateaspnetcore-6.0“ rel =“ nofollow noreferrer”

浏览器向托管服务器提出“前”请求
交叉原始资源,以检查服务器是否允许
实际请求。在该前飞行中,浏览器向标题发送了标题
指示将在实际中使用的HTTP方法和标题
请求。

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.

思慕 2025-02-02 08:53:19

我能够对其进行修改Web.config文件的操作:

<?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=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

BU我想让Visual Studio正确生成文件,而不是修复每个API发布/修改。

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=".\logs\stdout" 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文