首先,在ASP.NET Core 6.0应用程序项目中添加以下NuGet软件包:Microsoft.AspNetCore.Mvc.Core和Microsoft.AspNetCore.Mvc.NewtonsoftJson。
在Startup.cs文件中添加以下代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
namespace CountingApp
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
using Microsoft.AspNetCore.Mvc;
namespace CountingApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class CountingController : ControllerBase
{
[HttpGet("{num}")]
public IActionResult Get(string num)
{
int count = num.Length;
return Ok(new { count });
}
}
}
https://localhost:5001/counting/12345
这将返回以下结果:
{
"count": 5
}
上一篇:ASP.NETCore6.0:无法解析类型为'AutoMapper.IMapper'的服务
下一篇:ASP.NETCore6.0DataProtectionisdelayingtheentireservicestartup