应用程序完成后,无需阅读整个请求主体.net core 2.1.1

时间:2018-09-01 16:36:06

标签: 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 = 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

我在邮递员中的要求如下所示。 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();
        }
    }

11 个答案:

答案 0 :(得分:13)

setContentView(...)的错误信息通常在客户端发送不满足服务器要求的请求时发生。换句话说,它只是在进入动作之前发生,导致您无法通过动作主体中的断点来调试它。

例如,假设服务器上的一种操作方法:

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; } } 标头:

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

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

enter image description here

  1. 邮递员是否发送标头为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 的请求?确保已检查标题
  2. 如果step1不起作用,请单击Content-Type: application/json以显示当您向服务器发送请求时它发送的内容。

答案 1 :(得分:4)

在本地主机上调试时,在新的ASP.NET Core 2.1服务中发生了这件事,因为我在Startup.Configure中:

app.UseHttpsRedirection();

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

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

答案 2 :(得分:3)

可能有多种原因,其中可能是:–在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]

答案 3 :(得分:2)

我花了几个小时。我的问题是我有:

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

代替:

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

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

答案 4 :(得分: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)

答案 5 :(得分:0)

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

尝试一下吗?
 [AllowAnonymous]
 [HttpPost("register")]
 [Route("jsonbody")]
    public async Task<IActionResult> Register([FromBody] UserForRegisterDto userForRegisterDto){}

答案 6 :(得分:0)

我有同样的错误, 检查您是否可以将(AutoValidateAntiforgeryTokenAttribute)放入AddMvc Services

services.AddMvc(opt => {

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

答案 7 :(得分:0)

就我而言,查询是否错误:

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

解决&&错误AND后可以解决

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

答案 8 :(得分:0)

我这样解决了。来自

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

附加到[Route("api/authentication/")]/。我删除的[HttpPost("token")]处的斜杠。

答案 9 :(得分:0)

在远程Dotnet 2.2计算机上运行NGinxUbuntu 18.04时遇到相同的问题,得到了:

  

..无需阅读整个请求正文即可完成应用程序

在每个API调用上

。对我而言,解决方案是通过让我们加密通过CERTBot在主机上安装SSL证书,因为Dotnet不允许未加密的流量。

希望这对某人有帮助

答案 10 :(得分:0)

就我而言,根据实施情况,使用不正确的方法有时会导致此问题。例如尝试使用 POST 而不是 PATCH