Jor*_*ean 0 c# cors asp.net-core asp.net-core-webapi
我写了一个简单的ASP.NET Core 2.2 Web API. 该POST方法始终返回404,但 GET 请求成功。
public class TestPayload
{
public string test1 { get; set; }
public string test2 { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class TestController: ControllerBase
{
// POST api/create
[HttpPost]
public async Task<ActionResult<string>> Create([FromBody] TestPayload value)
{
return Ok("");
}
}
Run Code Online (Sandbox Code Playgroud)
我在 Angular HttpClient 前端收到 404 错误。
let headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.http.post<any>(`${config.apiUrl}/test/create`, { test1, test2}, { headers }).pipe(map(x => {
...
return x;
}));
Run Code Online (Sandbox Code Playgroud)
我在 Postman 中遇到同样的错误。
POST /api/Test/Create HTTP/1.1
Host: localhost:5001
Content-Type: application/json
cache-control: no-cache
Postman-Token: 4d304e86-013c-4be8-af07-f2262079000d
{ test1: "val1", test2: "val2" }------WebKitFormBoundary7MA4YWxkTrZu0gW--
Run Code Online (Sandbox Code Playgroud)
我在 Startup.cs 文件中启用了最宽松的 CORS 策略(用于测试),但它没有解决问题。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
我在 Visual Studio 的输出窗口中看到以下消息,这让我相信这是一个 CORS 错误,但我不知道我做错了什么。我的方法内的断点永远不会被命中,即使符号已加载并且它们在 GET 方法中被命中。
Microsoft.AspNetCore.Server.Kestrel:Information: Connection id "0HLKU1LFDTCPA", Request id "0HLKU1LFDTCPA:00000002": the application completed without reading the entire request body.
Run Code Online (Sandbox Code Playgroud)
这一切都在本地主机上运行。我已经在我的项目中安装了 Microsoft.AspNetCore.Cors (2.2.0) NuGet 包。
您尚未指定操作的路由。您可以更改您的帖子以转到 /api/Test 或设置操作的属性,如下所示:
[HttpPost("Create")]
public async Task<ActionResult<string>> Create([FromBody] TestPayload value)
{
return Ok("");
}
Run Code Online (Sandbox Code Playgroud)
或者
[HttpPost]
[Route("Create")]
public async Task<ActionResult<string>> Create([FromBody] TestPayload value)
{
return Ok("");
}
Run Code Online (Sandbox Code Playgroud)
或更新控制器路由以包含操作
[Route("api/[controller]/[action]")]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1566 次 |
| 最近记录: |