应用程序完成后,无需阅读整个请求主体.net core 2.1.1 [英] The application completed without reading the entire request body, .net core 2.1.1

查看:394
本文介绍了应用程序完成后,无需阅读整个请求主体.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);
        }
    }

当我使用邮递员发送请求时,它给了我404未找到状态代码,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.

我在邮递员中的要求看起来像这样。

My request in Postman looks like this.

我使用了数据传输对象(DTO)封装数据,因此删除了 UserForRegisterDto 并尝试使用字符串用户名字符串密码,但如下所示

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

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. 邮递员是否发送带有标头的请求内容类型:application / json ?确保已检查标题

  2. 如果step1不起作用,请单击代码以显示发送时确切发送的内容对服务器的请求。

  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天全站免登陆