I failed when i trying to post my method from console app. My datas come 0 or null. What is my mistake?

huangapple go评论65阅读模式
英文:

I failed when i trying to post my method from console app. My datas come 0 or null. What is my mistake?

问题

I failed when i trying to post my method from console app. My datas always come 0 or null. I'm sharing my codes and error screenshot.

我的控制台应用程序:

using MSE.DTO.DTOs.WorkStation;
using Newtonsoft.Json;
using System.Text;

var random = new Random();

var data = new WorkStationRandomValueDTO
{
    WorkStationId = random.Next(1, 100),
    Temperature = (decimal)Math.Round(random.NextDouble() * 100, 2),
    Pressure = (decimal)Math.Round(random.NextDouble() * 2000, 2),
    Status = random.Next(0, 1) == 1
};
var json = JsonConvert.SerializeObject(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");

using (var client = new HttpClient())
{
    var response = client.PostAsync("http://localhost:5002/WorkStationRandom/Post", content).Result;
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("Data saved successfully!");
    }
    else
    {
        Console.WriteLine("Failed to save data: " + response.StatusCode);
    }
}

我的Mvc Api控制器代码:

using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MSE.DataAccess.Context;
using MSE.DTO.DTOs.WorkStation;
using MSE.Entity.Entities.Concrete;
using System.Net;
using System.Text.Json.Serialization;
using System.Web.Http;
using FromBodyAttribute = System.Web.Http.FromBodyAttribute;
using HttpGetAttribute = System.Web.Http.HttpGetAttribute;
using HttpPostAttribute = System.Web.Http.HttpPostAttribute;
using RouteAttribute = System.Web.Http.RouteAttribute;

namespace MSE.Web.Controllers
{
    public class WorkStationRandomController : ApiController
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly IMapper _mapper;
        public WorkStationRandomController(ApplicationDbContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }

        [HttpPost]
        public IHttpActionResult Post(WorkStationRandomValueDTO data)
        {
            if (data != null)
            {
                var workStation = _mapper.Map<WorkStation>(data);
                _dbContext.WorkStations.Add(workStation);
                _dbContext.SaveChanges();

                return Ok();
            }
            else
            {
                return BadRequest("Data cannot be null.");
            }
        }
        [System.Web.Http.HttpGet]
        public string Get()
        {
            return "ok";
        }
    }
}

这是我的错误截图。我的数据总是这样。

我的错误

我正在尝试从控制台应用程序中发送数据,但我的数据始终是它们的默认值(0或null)。

英文:

I failed when i trying to post my method from console app. My datas always come 0 or null. I'm sharing my codes and error screenshot.

My Console App:

using MSE.DTO.DTOs.WorkStation;
using Newtonsoft.Json;
using System.Text;

var random = new Random();

var data = new WorkStationRandomValueDTO
{
    WorkStationId = random.Next(1, 100),
    Temperature = (decimal)Math.Round(random.NextDouble() * 100, 2),
    Pressure = (decimal)Math.Round(random.NextDouble() * 2000, 2),
    Status = random.Next(0, 1) == 1
};
var json = JsonConvert.SerializeObject(data);
var content = new StringContent(json, Encoding.UTF8, &quot;application/json&quot;);

using (var client = new HttpClient())
{
    var response = client.PostAsync(&quot;http://localhost:5002/WorkStationRandom/Post&quot;, content).Result;
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine(&quot;Data saved successfully!&quot;);
    }
    else
    {
        Console.WriteLine(&quot;Failed to save data: &quot; + response.StatusCode);
    }
}

My Mvc Api Controller Code :

using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MSE.DataAccess.Context;
using MSE.DTO.DTOs.WorkStation;
using MSE.Entity.Entities.Concrete;
using System.Net;
using System.Text.Json.Serialization;
using System.Web.Http;
using FromBodyAttribute = System.Web.Http.FromBodyAttribute;
using HttpGetAttribute = System.Web.Http.HttpGetAttribute;
using HttpPostAttribute = System.Web.Http.HttpPostAttribute;
using RouteAttribute = System.Web.Http.RouteAttribute;

namespace MSE.Web.Controllers
{
    public class WorkStationRandomController : ApiController
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly IMapper _mapper;
        public WorkStationRandomController(ApplicationDbContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }

        [HttpPost]
        public IHttpActionResult Post(WorkStationRandomValueDTO data)
        {
            if (data != null)
            {
                var workStation = _mapper.Map&lt;WorkStation&gt;(data);
                _dbContext.WorkStations.Add(workStation);
                _dbContext.SaveChanges();

                return Ok();
            }
            else
            {
                return BadRequest(&quot;Data cannot be null.&quot;);
            }
        }
        [System.Web.Http.HttpGet]
        public string Get()
        {
            return &quot;ok&quot;;
        }
    }
}

Here is the picture of my error. My datas always come like this.

My Error

I'm trying to post data from using a console application but my datas come their default values (0 or null).

答案1

得分: 1

在你的控制器中,在声明中为你的数据变量添加 [FromBody] 属性。

另外,可能是由于 MVC 尝试从发送的数据进行序列化到你的 WorkStationRandomValueDTO 时出现了问题。如果你将其更改为字符串,并在代码中手动执行序列化,或许你可以捕获到错误。

[HttpPost]
public IHttpActionResult Post([FromBody] string data)
{
    if (data != null)
    {
        var workStationRandomValue = JsonConvert.DeserializeObject<WorkStationRandomValueDTO>(data);
    }
}
英文:

In your Controller on the post add [FromBody] attribute to your data variable in the declaration.

It chould also be that the serialization that MVC is trying to do from the posted data into your WorkStationRandomValueDTO is failing. If you change it to be a string and do the serialization yourself in code after perhaps you can catch the error.

 [HttpPost]
        public IHttpActionResult Post(string data)
        {
            if (data != null)
            {
               var workStationRandonValue = JsonConvert.DeserializeObject&lt;WorkStationRandomValueDTO&gt;(data);

答案2

得分: 1

你的 Post 方法缺少 [FromBody] 属性。

请将代码调整如下:

[HttpPost]
public IHttpActionResult Post([FromBody] WorkStationRandomValueDTO data)
{
    if (data != null)
    {
        var workStation = _mapper.Map<WorkStation>(data);
        _dbContext.WorkStations.Add(workStation);
        _dbContext.SaveChanges();

        return Ok();
    }
    else
    {
        return BadRequest("Data cannot be null.");
    }
}
英文:

your Post method is missing the [FromBody] attribute.

Adjust the code as below

[HttpPost]
    public IHttpActionResult Post([FromBody] WorkStationRandomValueDTO data)
    {
        if (data != null)
        {
            var workStation = _mapper.Map&lt;WorkStation&gt;(data);
            _dbContext.WorkStations.Add(workStation);
            _dbContext.SaveChanges();

            return Ok();
        }
        else
        {
            return BadRequest(&quot;Data cannot be null.&quot;);
        }
    }

huangapple
  • 本文由 发表于 2023年2月10日 16:25:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定