应用程序在没有读取整个请求体的情况下完成,.net core 2.1.1 [英] The application completed without reading the entire request body, .net core 2.1.1

查看:32
本文介绍了应用程序在没有读取整个请求体的情况下完成,.net core 2.1.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a user register controller to register users with repository design pattern. My controller looks like this.

[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 not found 状态代码,API 报告请求已完成,而无需读取整个正文.

When I send a request using Postman, it gives me the the 404 not found status code, and API reports the request completed without reading the entire body.

我在 Postman 中的请求看起来像这样.

My request in Postman looks like this.

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

I have used Data Transfer Objects(DTO) to encapsulate data, I removed UserForRegisterDto and tried to use string username and string password, as follows but it did not work.

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

I have tried many online solutions for this, but so far nothing resolved my problem. Please help me to troubleshoot the issue, Thank you in advance. I'm running this API on Ubuntu 18.04

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

推荐答案

应用程序完成时没有读取整个请求体的错误信息经常发生在客户端发送未完成的请求时服务器的要求.换句话说,它发生在进入操作之前,导致您无法通过操作方法主体内的断点对其进行调试.

The error info of the application completed without reading the entire request body often occurs when the client send a request that doesn't fulfill the sever requirements . In other words , it happens just before entering the action , resulting that you cannot debug it via a breakpoint within the body of action method .

例如,假设在服务器上有一个操作方法:

For example , let's say a action method on the server :

[Route("api/[controller]")]
[ApiController]
public class DummyController : ControllerBase
{
    [HttpPost]
    public DummyDto PostTest([FromBody] DummyDto dto)
    {
        return dto;
    }
}

这里的 DummyDto 是一个用于保存信息的虚拟类:

The DummyDto here is a dummy class to hold information:

public class DummyDto 
{
    public int Id { get; set; }
}

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

When clients send a request with payload not well formatted

例如,以下发布请求,它没有 Content-Type: application/json 标头:

For example , the following post request , which doesn't have a Content-Type: application/json header :

POST https://localhost:44306/api/test HTTP/1.1
Accept : application/json

{ "id":5 }

将导致类似的错误信息:

will result in a similar error info :

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:

and the response from the server will be 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

对于你所描述的问题,我建议你应该检查以下列表:

As for the question you described , I suggest you should check the following list :

  1. 邮递员是否发送带有 Content-Type: application/json 标头的请求?确保您已检查标题
  2. 如果 step1 不起作用,请单击 code 以显示当您向服务器发送请求时它发送的确切内容.
  1. does the Postman send the request with a header of Content-Type: application/json ? make sure you have checked the header
  2. If step1 doesn't work , click the code to show what it sends exactly when you send a request to the server .

这篇关于应用程序在没有读取整个请求体的情况下完成,.net core 2.1.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆