.net core HttpClient.PutAsync返回400个错误请求(.Net Core/Blazor)

.net core HttpClient.PutAsync返回400个错误请求(.Net Core/Blazor),.net-core,blazor,webassembly,webapi,.net Core,Blazor,Webassembly,Webapi,我有一个Blazor WASM应用程序和一个.NetCore 3.1 WebAPI。我通过Blazor中推荐的服务类调用我的WebAPI。然而,每次对update的PUT调用我都会返回400个错误请求。它从未到达控制器。我已经通过APITester Chrome浏览器扩展测试了API控制器,并且端点工作正常。这让我相信这是HTTPClientCall中的一些东西 这是我的控制器上的API方法 [HttpPut("{id}")] public async Tas

我有一个Blazor WASM应用程序和一个.NetCore 3.1 WebAPI。我通过Blazor中推荐的服务类调用我的WebAPI。然而,每次对update的PUT调用我都会返回400个错误请求。它从未到达控制器。我已经通过APITester Chrome浏览器扩展测试了API控制器,并且端点工作正常。这让我相信这是HTTPClientCall中的一些东西

这是我的控制器上的API方法

[HttpPut("{id}")]
        public async Task<IActionResult> Update(int id, [FromBody] Country country)
        {
            if (id != country.Id)
            {
                return BadRequest();
            }

            try
            {
                await _repository.UpdateAsync(id, country);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (! await _repository.ExistsAsync(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }
这是我为Blazor WASM编写的Program.cs,它注册了HTTPClient

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            var baseAddress = new Uri("https://localhost:44395/api/");

            void RegisterTypedClient<TClient, TImplementation>(Uri apiBaseUrl)
                where TClient : class where TImplementation : class, TClient
            {
                builder.Services.AddHttpClient<TClient, TImplementation>(client =>
                {
                    client.BaseAddress = apiBaseUrl;
                });
            }

            RegisterTypedClient<ICountryService, CountryService>(baseAddress);          

            await builder.Build().RunAsync();
        }
公共静态异步任务主(字符串[]args)
{
var builder=WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add(“应用程序”);
var baseAddress=新Uri(“https://localhost:44395/api/");
无效RegisterTypedClient(Uri apiBaseUrl)
where TClient:class其中TImplementation:class,TClient
{
builder.Services.AddHttpClient(客户端=>
{
client.BaseAddress=apiBaseUrl;
});
}
RegisterTypedClient(基本地址);
等待builder.Build().RunAsync();
}
最后,这里是WebAPI中的Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Register EntityFramework Core Datacontext for Dependency Injection
            services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Register Repositories for Dependency Injection
            services.AddScoped<ICountryRepository, CountryRepository>();

            services.AddCors(options =>
            {
                options.AddPolicy("Open", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyHeader();
                    builder.AllowAnyMethod();
                });
            });

            services.AddControllers()
                    .AddMvcOptions(o =>
                    {
                        //Allow XML as a request Accept type
                        o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
                    });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseHttpsRedirection();      

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors("Open");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
//为依赖项注入注册EntityFramework核心Datacontext
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
//为依赖项注入注册存储库
services.addScope();
services.AddCors(选项=>
{
options.AddPolicy(“打开”,生成器=>
{
builder.AllowAnyOrigin();
builder.AllowAnyHeader();
builder.AllowAnyMethod();
});
});
services.AddControllers()
.addmvcopions(o=>
{
//允许XML作为请求接受类型
o、 Add(新的XmlDataContractSerializerOutputFormatter());
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
应用程序UseCors(“开放”);
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}

尝试将
[HttpPut(“{id}”)]
更改为
[HttpPut,Route({id}”)]
同样,这是错误的:
var response=wait\u httpClient.PutAsync(“Countries/{id}”,content)
您从不填写
{id}
。它应该是
var response=await\u httpClient.PutAsync($“Countries/{id}”,content)就是这样。总是小事。谢谢你,伙计
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Register EntityFramework Core Datacontext for Dependency Injection
            services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Register Repositories for Dependency Injection
            services.AddScoped<ICountryRepository, CountryRepository>();

            services.AddCors(options =>
            {
                options.AddPolicy("Open", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyHeader();
                    builder.AllowAnyMethod();
                });
            });

            services.AddControllers()
                    .AddMvcOptions(o =>
                    {
                        //Allow XML as a request Accept type
                        o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
                    });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseHttpsRedirection();      

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors("Open");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }