C# 应用程序已完成,但未读取整个请求正文.net core 2.1.1
我已经创建了一个用户注册控制器,用存储库设计模式注册用户。我的控制器看起来像这样C# 应用程序已完成,但未读取整个请求正文.net core 2.1.1,c#,.net-core,asp.net-core-webapi,asp.net-core-2.1,C#,.net Core,Asp.net Core Webapi,Asp.net Core 2.1,我已经创建了一个用户注册控制器,用存储库设计模式注册用户。我的控制器看起来像这样 [Route("api/[controller]")] public class AuthController : Controller { private readonly IAuthRepository _repo; public AuthController(IAuthRepository repo) { _repo =
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IAuthRepository _repo;
public AuthController(IAuthRepository repo)
{
_repo = repo;
}
[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto){
// validate request
if(!ModelState.IsValid)
return BadRequest(ModelState);
userForRegisterDto.Username = userForRegisterDto.Username.ToLower();
if(await _repo.UserExists(userForRegisterDto.Username))
return BadRequest("Username is already taken");
var userToCreate = new User{
Username = userForRegisterDto.Username
};
var createUser = await _repo.Register(userToCreate, userForRegisterDto.Password);
return StatusCode(201);
}
}
public class UserForRegisterDto
{
[Required]
public string Username { get; set; }
[Required]
[StringLength(8, MinimumLength =4, ErrorMessage = "You must specify a password between 4 and 8 characters.")]
public string Password { get; set; }
}
UserForRegisterDto
如下所示
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IAuthRepository _repo;
public AuthController(IAuthRepository repo)
{
_repo = repo;
}
[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto){
// validate request
if(!ModelState.IsValid)
return BadRequest(ModelState);
userForRegisterDto.Username = userForRegisterDto.Username.ToLower();
if(await _repo.UserExists(userForRegisterDto.Username))
return BadRequest("Username is already taken");
var userToCreate = new User{
Username = userForRegisterDto.Username
};
var createUser = await _repo.Register(userToCreate, userForRegisterDto.Password);
return StatusCode(201);
}
}
public class UserForRegisterDto
{
[Required]
public string Username { get; set; }
[Required]
[StringLength(8, MinimumLength =4, ErrorMessage = "You must specify a password between 4 and 8 characters.")]
public string Password { get; set; }
}
我已经尝试了许多在线解决方案,但到目前为止,没有解决我的问题。请帮我解决问题,提前谢谢。我在Ubuntu 18.04上运行这个API
编辑: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)
{
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors();
services.AddScoped<IAuthRepository, AuthRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseMvc();
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(x=>x.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors();
services.addScope();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseHsts();
}
app.UseCors(x=>x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseMvc();
}
}
您可以通过添加请求方法[Route(“jsonbody”)来尝试吗
[AllowAnonymous]
[HttpPost(“注册”)]
[路线(“jsonbody”)]
公共异步任务寄存器([FromBody]UserForRegisterTo UserForRegisterTo){
当客户端发送不满足服务器要求的请求时,通常会出现未读取整个请求正文而完成的应用程序的错误信息。换句话说,它发生在进入操作之前,导致无法通过操作体方法中的断点对其进行调试
例如,假设服务器上有一个操作方法:
[Route("api/[controller]")]
[ApiController]
public class DummyController : ControllerBase
{
[HttpPost]
public DummyDto PostTest([FromBody] DummyDto dto)
{
return dto;
}
}
DummyDto
这里有一个虚拟类来保存信息:
public class DummyDto
{
public int Id { get; set; }
}
当客户端发送负载格式不正确的请求时
例如,以下post请求没有内容类型:application/json
头:
POST https://localhost:44306/api/test HTTP/1.1
Accept : application/json
{ "id":5 }
将导致类似的错误信息:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44306/api/test 10
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1.9319ms 404
Microsoft.AspNetCore.Server.Kestrel:Information: Connection id "0HLGH8R93RPUO", Request id "0HLGH8R93RPUO:00000002": the application completed without reading the entire request body.
服务器的响应将是404
:
HTTP/1.1 404 Not Found
Server: Kestrel
X-SourceFiles: =?UTF-8?B?RDpccmVwb3J0XDIwMThcOVw5LTFcU08uQXV0aFJlYWRpbmdXaXRob3V0RW50aXRlQm9keVxBcHBcQXBwXGFwaVx0ZXN0?=
X-Powered-By: ASP.NET
Date: Mon, 03 Sep 2018 02:42:53 GMT
Content-Length: 0
关于你所描述的问题,我建议你检查以下列表:
Content-Type:application/json
的请求?确保已检查标题代码
,以显示向服务器发送请求时它发送的确切内容services.AddMvc(opt => {
//Prevent CSF Attake For POST,PUT,DELETE Verb
//opt.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})
我也有同样的错误(即使是“Content-Type:application/json”),但在动作动词中添加“{id}”对我来说是有效的
i、 e.从
[HttpPatch]
[ActionName("Index")]
[Authorize(Policy = "Model")]
public async Task<JsonResult> Update([FromRoute]int id, int modelId, [FromBody]Device device)
[HttpPatch]
[行动名称(“索引”)]
[授权(Policy=“Model”)]
公共异步任务更新([FromRoute]int-id,int-modelId,[FromBody]设备)
到
[HttpPatch(“{id}”)]
[行动名称(“索引”)]
[授权(Policy=“Model”)]
公共异步任务更新([FromRoute]int-id,int-modelId,[FromBody]设备)
(asp.net core 2.1)有多种原因,其中一种可能是:–Visual Studio中的缓存--
在我的情况下,问题是否错误:
SELECT * FROM dbo.person WHERE login= 'value' && pass = 'value'
在修复和&
错误和正常后解决
SELECT * FROM dbo.person WHERE login= 'value' AND pass = 'value'
在localhost中调试时,我在新的ASP.NET Core 2.1服务中遇到了这种情况,因为我在启动时遇到了问题。配置:
app.UseHttpsRedirection();
我在本地调试时停用了此设置:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHttpsRedirection();
}
我就这样解决了。从
namespace AuthenticationService.Controllers
{
[Route("api/authentication")]
[ApiController]
public class AuthenticationController : ControllerBase
{
[HttpPost("/token")]
public IActionResult GenerateToken([FromBody] LoginRest loginRest)
{
到[路由(“api/authentication/”)
,并附加/
。我删除了[HttpPost(“token”)]
处的斜杠。在远程Ubuntu 18.04
计算机上运行Dotnet 2.2
和NGinx
时遇到了同样的问题,得到了:
。应用程序在未读取整个请求正文的情况下完成
在每个API调用上。对我来说,解决这个问题的办法是通过Let's encrypt的CERTBot在主机上安装SSL证书,因为Dotnet
不允许未加密的流量
希望这能帮助别人我花了几个小时在这上面。我的问题是我有:
[HttpPut("{matchGuidStr}/join")]
public async Task<IActionResult> JoinNewMatch (string matchGuidStr) {
[HttpPut(“{matchGuidStr}/join”)]
公共异步任务JoinNewMatch(字符串matchGuidStr){
而不是:
[HttpPut("{matchGuidStr}/join")]
public async Task<IActionResult> JoinNewMatch (string matchGuidStr, [FromBody] Payloads.JoinGamePayload payload) {
[HttpPut(“{matchGuidStr}/join”)]
公共异步任务JoinNewMatch(字符串matchGuidStr,[FromBody]有效载荷。JoinGamePayload有效载荷){
基本上,我的路线根本不关心请求主体(有意地)但我仍然需要将其作为参数传递。哎呀!在我的例子中,使用不正确的方法有时会导致此问题,具体取决于实现。例如,尝试使用POST
而不是PATCH时,是否尝试在方法上设置断点,以查看通过postman调用时是否命中该方法?可以吗您还提供了startup.cs?是的,我尝试过。它没有被击中。startup.cs被添加到问题中。您可以尝试删除services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);然后重试吗?您可以添加一个简单的GET方法,返回“Hello World”吗字符串连接到您的控制器并尝试通过浏览器调用?我过去在Cors
方面遇到过问题。有时是因为将allowredentials
包含在AllowAnyOrigin
中
[HttpPut("{matchGuidStr}/join")]
public async Task<IActionResult> JoinNewMatch (string matchGuidStr) {
[HttpPut("{matchGuidStr}/join")]
public async Task<IActionResult> JoinNewMatch (string matchGuidStr, [FromBody] Payloads.JoinGamePayload payload) {