Razor Page POST данные формы для контроллера - PullRequest
0 голосов
/ 14 января 2020

Я разработал очень простое веб-приложение. NET Core 2.2 с использованием шаблона WebAPI. Я смог успешно протестировать свои конечные точки с помощью Почтальона и хотел бы добавить простой веб-интерфейс с использованием уже доступных страниц бритвы (.cs html)

Проблема: Я не могу успешно нажать моя конечная точка контроллера, использующая мою страницу бритвы. Я попытался украсить свою конечную точку с / без «[FromBody]».

Мой chrome отладчик перехватывает следующую транзакцию: Registration Form Error

Ошибка на веб-странице:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLSP5DVTEH9B:00000008"}

В выводе указано, что маршрут соответствует: output

Код:

У меня есть следующая страница бритвы: Registration.cs html

@page
@using Microsoft.AspNetCore.Mvc.Rendering
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model RegistrationModel
@{
    ViewData["Title"] = "Registration";
}
<h2>@ViewData["Title"]</h2>

@{
    using (Html.BeginForm("Register", "Registration", FormMethod.Post))
    {
        <label>Username</label>
        @Html.TextBoxFor(m => m.Username)

        <br />

        <label>Password</label>
        @Html.TextBoxFor(m => m.Password)

        <br />

        <label>Role</label>
        <label>
            @Html.RadioButtonFor(m => m.Role, "0")
            1
        </label>
        <label>
            @Html.RadioButtonFor(m => m.Role, "1")
            2
        </label>

        <br />

        <input type="submit" value="Register" />
    }
}

Registration.cs html .cs

namespace RandomContent.Pages
{
    public class RegistrationModel : PageModel
    {
        public string Message { get; set; }

        public void OnGet()
        {
            Message = "Fill out the form below to be registered with the application.";
        }

        [Required]
        [Display(Name = "User name")]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required]
        [Display(Name = "Role")]
        public Role Role { get; set; }
    }
}

Контроллер:

namespace RandomContent.Controllers
{
    [Authorize]
    [ApiController]
    [Route("Registration")]
    public class RegistrationController : ControllerBase
    {
        private readonly IRegistrationService _registrationService;

        public RegistrationController(IRegistrationService registrationService)
        {
            _registrationService = registrationService;
        }

        /// <summary>
        /// Creates a new user
        /// Will return a bad request if the user could not be added to the db
        /// or the user already exists
        /// </summary>
        /// <param name="userParam"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("Register")]
        public IActionResult Register(RegistrationModel userParam)
        {
            //Validations
            if (!Enum.IsDefined(typeof(Role), userParam.Role))
                return BadRequest("Must select valid Role for user");
            if (string.IsNullOrWhiteSpace(userParam.Username))
                return BadRequest("Must enter a username");
            if (string.IsNullOrWhiteSpace(userParam.Password))
                return BadRequest("Must enter a password");

            //Register user
            var user = _registrationService.Register(userParam);
            if (user != null) return Ok(user);
            return BadRequest("Could not create user profile. They username may have been taken, or something else happened.");
        }

    }
}

Вопрос: Как я могу успешно разместить данные формы в моем контроллере? Я даже не могу отладить свой контроллер, пока не отправлю запрос от почтальона.

Полный проект можно найти на Github: https://github.com/bestfriendkumar/RandomContent

...