应用程序在没有读取整个请求主体的情况下完成,.net core 2.1.1

问题描述 投票:10回答:7

我创建了一个用户注册控制器来注册用户的存储库设计模式。我的控制器看起来像这样。

[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);
        }
    }

当我使用Postman发送请求时,它会向我提供404未找到的状态代码,并且API会在不读取整个正文的情况下报告请求已完成。

enter image description here

我在Postman的请求看起来像这样。 enter image description here

我已经使用数据传输对象(DTO)来封装数据,我删除了UserForRegisterDto并尝试使用string usernamestring password,如下所示,但它不起作用。

public async Task<IActionResult> Register([FromBody] string username, string password)

UserForRegisterDto看起来像这样。

 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();
        }
    }
c# .net-core asp.net-core-webapi asp.net-core-2.1
7个回答
13
投票

当客户端发送不满足服务器要求的请求时,经常会出现the application completed without reading the entire request body的错误信息。换句话说,它恰好在进入操作之前发生,导致您无法通过操作体方法中的断点对其进行调试。

例如,假设服务器上有一个action方法:

[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; }
}

当客户端发送请求时,有效负载格式不正确

例如,以下发布请求,其中没有Content-Type: 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

至于你描述的问题,我建议你检查以下列表:

enter image description here

  1. 邮递员是否发送了带有Content-Type: application/json标题的请求?确保您已检查标题
  2. 如果step1不起作用,请单击code以显示向服务器发送请求时的确切发送内容。

4
投票

在localhost中进行调试时,我遇到了一个新的ASP.NET Core 2.1服务,因为我在Startup.Configure中:

app.UseHttpsRedirection();

我在本地调试时停用了此设置:

if (env.IsDevelopment())
{
     app.UseDeveloperExceptionPage();
}
else
{
     app.UseHttpsRedirection();
}

2
投票

可能有多种原因可以解决: - 在Visual Studio中缓存 -

1.Close all the instances of visual studios, run Developer command prompt with Admin rights.
2.git clean -xfd [Your Repository to remove all dependencies and existing soln file]
3.take the latest build and run . [Make Endpoint AllowAnonymous]

1
投票

我有同样的错误(即使使用“Content-Type:application / json”),但在动作动词中添加“{id}”,即为

    [HttpPatch]
    [ActionName("Index")]
    [Authorize(Policy = "Model")]
    public async Task<JsonResult> Update([FromRoute]int id, int modelId, [FromBody]Device device)

    [HttpPatch("{id}")]
    [ActionName("Index")]
    [Authorize(Policy = "Model")]
    public async Task<JsonResult> Update([FromRoute]int id, int modelId, [FromBody]Device device)

(asp.net核心2.1)


0
投票

你可以通过添加请求方法[Route(“jsonbody”)]来尝试

 [AllowAnonymous]
 [HttpPost("register")]
 [Route("jsonbody")]
    public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto){}

0
投票

我有相同的错误,检查你可能在AddMvc服务中放入(AutoValidateAntiforgeryTokenAttribute)

services.AddMvc(opt => {

            //Prevent CSF Attake For POST,PUT,DELETE Verb
            //opt.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
        })

0
投票

在我的情况下,查询错误:

SELECT * FROM dbo.person WHERE login= 'value' && pass = 'value'

解决了修复&&错误的AND确定

SELECT * FROM dbo.person WHERE login= 'value' AND pass = 'value'
© www.soinside.com 2019 - 2024. All rights reserved.