代码之家  ›  专栏  ›  技术社区  ›  Nishan

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

  •  10
  • Nishan  · 技术社区  · 8 年前

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

    [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发送请求时,它会给我404notfound状态代码,API报告请求已完成,而不读取整个正文。

    enter image description here

    我对邮递员的要求是这样的。 enter image description here

    我已经使用数据传输对象(DTO)来封装数据,我删除了 UserForRegisterDto 并试图利用 string username string password

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

    UserForRegisterTo用户 看起来像这样。

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

    编辑: 启动.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();
            }
        }
    
    7 回复  |  直到 7 年前
        1
  •  26
  •   itminus    8 年前

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

    [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请求没有 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. 内容类型:application/json ? 确保您已经检查了标题
    2. 如果步骤1不起作用,请单击 code
        2
  •  27
  •   Vilmir    7 年前

    这件事发生在我的新生活中ASP.NET在localhost中调试时使用了核心2.1服务,因为启动。配置:

    app.UseHttpsRedirection();
    

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

    if (env.IsDevelopment())
    {
         app.UseDeveloperExceptionPage();
    }
    else
    {
         app.UseHttpsRedirection();
    }
    
        3
  •  4
  •   dinesh kandpal    7 年前

    其中一个原因可能有多种:visualstudio中的缓存--

    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]
    
        4
  •  2
  •   Robert    7 年前

    i、 e.从

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

        5
  •  2
  •   kuzdu    7 年前

    我就这样解决了。从

    namespace AuthenticationService.Controllers
    {
        [Route("api/authentication")]
        [ApiController]
        public class AuthenticationController : ControllerBase
        {
            [HttpPost("/token")]
            public IActionResult GenerateToken([FromBody] LoginRest loginRest)
            {
    

    [Route("api/authentication/")] 加上一个额外的 / . 对…的猛砍 [HttpPost("token")] 我搬走了。

        6
  •  2
  •   Haroun Hajem    7 年前

    也有同样的问题 Dotnet 2.2 NGinx Ubuntu 18.04 -机器,有一个:

    .. . 应用程序在未读取整个请求正文的情况下完成

    让我们加密 ,自 Dotnet

        7
  •  2
  •   dak    6 年前

    我花了好几个小时在这上面。我的问题是:

    [HttpPut("{matchGuidStr}/join")]
    public async Task<IActionResult> JoinNewMatch (string matchGuidStr) {
    

    而不是:

    [HttpPut("{matchGuidStr}/join")]
    public async Task<IActionResult> JoinNewMatch (string matchGuidStr, [FromBody] Payloads.JoinGamePayload payload) {
    

    基本上,我的路由根本不关心请求主体(有意),但我仍然需要将其作为参数传递。哎呀!

        8
  •  1
  •   Zeyit Başar    8 年前

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

     [AllowAnonymous]
     [HttpPost("register")]
     [Route("jsonbody")]
        public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto){}
    
        9
  •  0
  •   Abdulaziz Alrashed    7 年前

    检查是否将(AutoValidateAntiforgeryTokenAttribute)放入AddMvc服务中

    services.AddMvc(opt => {
    
                //Prevent CSF Attake For POST,PUT,DELETE Verb
                //opt.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            })
    
        10
  •  -2
  •   Diego Venâncio    7 年前

    在我看来,这个问题是不是错了:

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

    && 错误的 AND

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