{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId"

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

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId"

问题

Here's the translation of the code portion you provided:

我正在尝试使用我的 Web API 创建一个站点。使用简单的 GET 功能一切都正常。但是当我创建一个 POST 方法并添加了一个 Razor 页面时,每次尝试打开该页面时,都会收到相同的消息:{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"发生了一个或多个验证错误。","status":400,"traceId":"00-b6df63a1f0833724ea5e9547634bec47-0bc084ebe01d4967-00","errors":{"workerId":["值 'register' 无效."]}}。在使用 Swagger 时,代码可以正常工作。
用于注册的 WorkerController 片段:

[HttpPost("register")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
public IActionResult Register(Worker workerCreate)
{
    if (workerCreate == null)
        return BadRequest(ModelState);

    var worker = _workerRepository.GetWorkers()
        .Where(x => x.Email.Trim().ToUpper() == workerCreate.Email.ToUpper()
        || x.PhoneNum.Trim().ToUpper() == workerCreate.PhoneNum.ToUpper())
        .FirstOrDefault();

    if (worker != null)
    {
        ModelState.AddModelError("", "Worker already exists");
        return StatusCode(422, ModelState);
    }

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (!_workerRepository.Register(workerCreate))
    {
        ModelState.AddModelError("", "保存时出现问题");
        return StatusCode(500, ModelState);
    }

    return Ok("成功注册");
}

Web 应用程序中的 WorkerController 代码:

public IActionResult Register()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> Register(WebApplicationWorker worker)
{

    var apiUrl = "https://localhost:7071/api/Worker/register";
    worker.Id = 0;

    string jsonPayload = JsonConvert.SerializeObject(worker);
    HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
    using (var response = await _httpClient.PostAsync(apiUrl, content))
    {
        if (response.IsSuccessStatusCode)
        {
            return RedirectToAction("Workers");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "注册错误");
        }
    }
    return View(worker);
}

WebApplicationWorkerModel 代码:

using System.Text.Json.Serialization;

namespace CourseWorkZakharov.Web.Models
{
    public class WebApplicationWorker
    {
        [JsonIgnore]
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public string PhoneNum { get; set; }
        public string Email { get; set; }
        public string Degree { get; set; }
        public string WorkExp { get; set; }
        public string Description { get; set; }
        public string ImagePath { get; set; }
        public string Password { get; set; }
    }
}

注册页面的代码:

@model WebApplicationWorker

<h1>用户注册</h1>

@using (Html.BeginForm("Register", "Worker", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name)
    </div>
    <div>
        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m => m.LastName)
    </div>
    <div>
        @Html.LabelFor(m => m.PhoneNum)
        @Html.TextBoxFor(m => m.PhoneNum)
    </div>
    <div>
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email)
    </div>
    <div>
        @Html.LabelFor(m => m.Degree)
        @Html.TextBoxFor(m => m.Degree)
    </div>
    <div>
        @Html.LabelFor(m => m.WorkExp)
        @Html.TextBoxFor(m => m.WorkExp)
    </div>
    <div>
        @Html.LabelFor(m => m.Description)
        @Html.TextBoxFor(m => m.Description)
    </div>
    <div>
        @Html.LabelFor(m => m.ImagePath)
        @Html.TextBoxFor(m => m.ImagePath, new { type = "file" })
    </div>
    <div>
        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password)
    </div>

    <button type="submit">注册</button>
}

希望对你有所帮助。

英文:

I am trying to create a site using my web api. Everything went fine with simple GET function. But when i created a POST method and added a razor page to it, any time i try to open that page i get the same message: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-b6df63a1f0833724ea5e9547634bec47-0bc084ebe01d4967-00","errors":{"workerId":["The value 'register' is not valid."]}}. The code works when using swagger.
WorkerController fragmet for registration:

[HttpPost(&quot;register&quot;)]
        [ProducesResponseType(204)]
        [ProducesResponseType(400)]
        public IActionResult Register(Worker workerCreate)
        {
            if (workerCreate == null)
                return BadRequest(ModelState);

            var worker = _workerRepository.GetWorkers()
                .Where(x =&gt; x.Email.Trim().ToUpper() == workerCreate.Email.ToUpper()
                || x.PhoneNum.Trim().ToUpper() == workerCreate.PhoneNum.ToUpper())
                .FirstOrDefault();

            if (worker != null)
            {
                ModelState.AddModelError(&quot;&quot;, &quot;Worker already exists&quot;);
                return StatusCode(422, ModelState);
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            

            if (!_workerRepository.Register(workerCreate))
            {
                ModelState.AddModelError(&quot;&quot;, &quot;Something went wrong while saving&quot;);
                return StatusCode(500, ModelState);
            }

            return Ok(&quot;Successfully registered&quot;);
        }

Code of WorkerController in Web Application:

public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task&lt;IActionResult&gt; Register(WebApplicationWorker worker)
        {

            var apiUrl = &quot;https://localhost:7071/api/Worker/register&quot;;
            worker.Id = 0;

            string jsonPayload = JsonConvert.SerializeObject(worker);
            HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, &quot;application/json&quot;);
            using (var response = await _httpClient.PostAsync(apiUrl, content))
            {
                if (response.IsSuccessStatusCode)
                {
                    return RedirectToAction(&quot;Workers&quot;);
                }
                else
                {
                    ModelState.AddModelError(string.Empty, &quot;Ошибка регистрации&quot;);
                }
            }
            return View(worker);
        }

Code of WebApplicationWorkerModel:

using System.Text.Json.Serialization;

namespace CourseWorkZakharov.Web.Models
{
    public class WebApplicationWorker
    {
        [JsonIgnore]
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public string PhoneNum { get; set; }
        public string Email { get; set; }
        public string Degree { get; set; }
        public string WorkExp { get; set; }
        public string Description { get; set; }
        public string ImagePath { get; set; }
        public string Password { get; set; }
    }
}

Code of Register page:

@model WebApplicationWorker

&lt;h1&gt;Регистрация пользователя&lt;/h1&gt;

@using (Html.BeginForm(&quot;Register&quot;, &quot;Worker&quot;, FormMethod.Post, new { enctype = &quot;multipart/form-data&quot; }))
{
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.Name)
        @Html.TextBoxFor(m =&gt; m.Name)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.LastName)
        @Html.TextBoxFor(m =&gt; m.LastName)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.PhoneNum)
        @Html.TextBoxFor(m =&gt; m.PhoneNum)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.Email)
        @Html.TextBoxFor(m =&gt; m.Email)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.Degree)
        @Html.TextBoxFor(m =&gt; m.Degree)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.WorkExp)
        @Html.TextBoxFor(m =&gt; m.WorkExp)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.Description)
        @Html.TextBoxFor(m =&gt; m.Description)
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.ImagePath)
        @Html.TextBoxFor(m =&gt; m.ImagePath, new { type = &quot;file&quot; })
    &lt;/div&gt;
    &lt;div&gt;
        @Html.LabelFor(m =&gt; m.Password)
        @Html.PasswordFor(m =&gt; m.Password)
    &lt;/div&gt;

    &lt;button type=&quot;submit&quot;&gt;Зарегистрироваться&lt;/button&gt;
}

Huge thanks in advance

I have tried removing the main part of the code (under [HttpPost]) and emptying the page. didn't help at all

答案1

得分: 0

在进行一些研究后,我成功找到了一个名叫"tick"的家伙,他是所有混乱的根源。这家伙位于我的API的WorkerController中。

[HttpGet("{workerId}")]
[ProducesResponseType(200, Type = typeof(Worker))]
[ProducesResponseType(400)]
public IActionResult GetWorker(int workerId)
{
    if(!_workerRepository.WorkerExists(workerId))
        return NotFound();
    var worker = _workerRepository.GetWorker(workerId);
    if (worker == null)
        return BadRequest(ModelState);
    return Ok(worker);
}

因为它的路由是"api/Worker/{workerId}",而注册路由是"api/worker/register",程序误将其解释为我正在传递"register"作为workerId。

英文:

After a bit of research I managed to find a "tick" who is causing all the mischief. The bastard was in my WorkerController of my API
`

[HttpGet("{workerId}")]

    [ProducesResponseType(200, Type = typeof(Worker))]
    [ProducesResponseType(400)]
    public IActionResult GetWorker(int workerId)
    {
        if(!_workerRepository.WorkerExists(workerId))
            return NotFound();
        var worker = _workerRepository.GetWorker(workerId);
        if (worker == null)
            return BadRequest(ModelState);
        return Ok(worker);
    }`

because its route is "api/Worker/{workerId}" and register route is "api/worke/register" program took it as i was passing "register" as workerId

huangapple
  • 本文由 发表于 2023年5月13日 17:36:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242031.html
匿名

发表评论

匿名网友

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

确定