Blazor 和 WebApi 在同一个解决方案中:为什么 POST 响应 405:方法不允许?
Blazor and WebApi in same solution: Why is the POST response 405: Method not allowed?
我在一个解决方案中有两个项目:
- WebApi
- Blazor wasm
我从
开始这两个项目
在Program.cs中添加了一个外部HttpClient
builder.Services.AddHttpClient("WEbApi", client => client.BaseAddress = new Uri("http://localhost:12639"));
来自我的 Index.razor.cs
的发件人
using System.Net.Http;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Components;
public partial class Index
{
[Inject] private IHttpClientFactory ClientFactory { get; set; }
public void Send()
{
var client = ClientFactory.CreateClient("WEbApi");
var res = client.PostAsJsonAsync("order","FOO");
}
}
在 WEbApi 项目中收到的控制器代码:
using Microsoft.AspNetCore.Mvc;
[Route("[controller]")]
public class OrderController : Controller
{
[HttpGet]
public IActionResult Index()
{
return Ok("GET done");
}
[HttpPost]
public IActionResult ExecuteOrder([FromBody] string order)
{
return Ok("POST done");
}
}
GET 请求returnOK。
问题:
client.PutAsJsonAsync("order","FOO") 响应 405:方法不允许(通过 wireshark 侦听)。
我用 Postman 尝试 POST,成功了!
我必须在 tzh WebApi 项目中配置 CORS。现在可以了。
将此代码插入 public void Configure() 中 Startup.cs
app.UseCors(cors => cors
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials()
);
我在一个解决方案中有两个项目:
- WebApi
- Blazor wasm
我从
开始这两个项目在Program.cs中添加了一个外部HttpClient
builder.Services.AddHttpClient("WEbApi", client => client.BaseAddress = new Uri("http://localhost:12639"));
来自我的 Index.razor.cs
的发件人using System.Net.Http;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Components;
public partial class Index
{
[Inject] private IHttpClientFactory ClientFactory { get; set; }
public void Send()
{
var client = ClientFactory.CreateClient("WEbApi");
var res = client.PostAsJsonAsync("order","FOO");
}
}
在 WEbApi 项目中收到的控制器代码:
using Microsoft.AspNetCore.Mvc;
[Route("[controller]")]
public class OrderController : Controller
{
[HttpGet]
public IActionResult Index()
{
return Ok("GET done");
}
[HttpPost]
public IActionResult ExecuteOrder([FromBody] string order)
{
return Ok("POST done");
}
}
GET 请求returnOK。
问题: client.PutAsJsonAsync("order","FOO") 响应 405:方法不允许(通过 wireshark 侦听)。
我用 Postman 尝试 POST,成功了!
我必须在 tzh WebApi 项目中配置 CORS。现在可以了。
将此代码插入 public void Configure() 中 Startup.cs
app.UseCors(cors => cors
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials()
);