英文:
{"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("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("", "Something went wrong while saving");
return StatusCode(500, ModelState);
}
return Ok("Successfully registered");
}
Code of WorkerController in Web Application:
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);
}
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
<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>
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论