ASP. NET Базовая ошибка HTTP 405 - неправильный метод при маршрутизации на действие пост-контроллера - PullRequest
0 голосов
/ 10 апреля 2020

Итак, у меня есть AppointmentController, у которого есть действие AcceptAppointment. Метод должен быть POST. Но каждый раз, когда я нажимаю на ссылку ActionLink на моей странице Razor, я получаю следующую ошибку. Эта страница не работает. Если проблема не устранена, обратитесь к владельцу сайта. ОШИБКА HTTP 405

Вот мой контроллер:

[Authorize]
public class AppointmentController : Controller
{
    private readonly IAppointmentsService appointmentsService;

    public AppointmentController(IAppointmentsService appointmentsService)
    {
        this.appointmentsService = appointmentsService;
    }

    public IActionResult Index()
    {
        return this.View();
    }

    public IActionResult GetAppointmentFromNotification(string id)
    {
        var notification = this.appointmentsService.GetAppointmentFromNotificationById(id);
        var startTimeMinutes = notification.StartTime.Minute == 0 ? "00" : notification.StartTime.Minute.ToString();
        var endTimeMinutes = notification.EndTime.Minute == 0 ? "00" : notification.EndTime.Minute.ToString();

        var startTime = notification.StartTime.Hour.ToString() + ":" + startTimeMinutes;
        var endTime = notification.EndTime.Hour.ToString() + ":" + endTimeMinutes;

        var viewModel = new AppointmentControlViewModel
        {
            Id = notification.Id,
            Date = notification.Date.ToString("dddd, dd MMMM yyyy", new CultureInfo("bg-BG")),
            StartTime = startTime,
            EndTime = endTime,
            Dogsitter = notification.Dogsitter,
            Owner = notification.Owner,
        };

        return this.View(viewModel);
    }

    [HttpPost]
    public async Task<IActionResult> AcceptAppointment(string id)
    {
        var requestedAppointment = this.appointmentsService.GetAppointmentFromNotificationById(id);

        var appointment = new Appointment
        {
            Status = AppointmentStatus.Unprocessed,
            Timer = 0,
            Date = requestedAppointment.Date,
            StartTime = requestedAppointment.StartTime,
            EndTime = requestedAppointment.EndTime,
            OwnerId = requestedAppointment.OwnerId,
            DogsitterId = requestedAppointment.DogsitterId,
        };

        var notificationToOwner = new Notification
        {
            ReceivedOn = DateTime.UtcNow,
            Content = $"Your request has been sent to <p class=\"text-amber\">{requestedAppointment.Dogsitter.FirstName}</p>",
            OwnerId = requestedAppointment.OwnerId,
            DogsitterId = requestedAppointment.DogsitterId,
        };

        await this.appointmentsService.CreateNewAppointment(appointment);
        await this.appointmentsService.RemoveNotification(requestedAppointment);
        await this.appointmentsService.SendNotificationForAcceptedAppointment(notificationToOwner);

        return this.RedirectToAction("Index");
    }

    [HttpPost]
    public async Task<IActionResult> RejectAppointment(string id)
    {
        var requestedAppointment = this.appointmentsService.GetAppointmentFromNotificationById(id);

        var notificationToOwner = new Notification
        {
            ReceivedOn = DateTime.UtcNow,
            Content = $"Вашата заявка до <p class=\"text-amber\">{requestedAppointment.Dogsitter.FirstName} беше <b class=\"red-text\">отхвърлена</b></p>",
            OwnerId = requestedAppointment.OwnerId,
            DogsitterId = requestedAppointment.DogsitterId,
        };

        await this.appointmentsService.RemoveNotification(requestedAppointment);
        await this.appointmentsService.SendNotificationForAcceptedAppointment(notificationToOwner);

        return this.RedirectToAction("Index");
    }
}

Вот мой Razor View:

@model DogCarePlatform.Web.ViewModels.Dogsitter.AppointmentControlViewModel
@{
ViewData["Title"] = "GetAppointmentFromNotification";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="col s6 m6 center">
<div class="row center">
    <div class="col s12 ">
        <div class="card hoverable #4db6ac teal lighten-2">
            <div class="card-content white-text">
                <span class="card-title">Уговаряне на дата и час за гледане на кучета</span>
                <p class="row">
                    Моля изберете дали искате уговорката да бъде записана или не. Ако желаете да потвърдите уговорката за дадената дата моля натиснете бутон "Приемам". В противен случай изберете бутон "Отказвам".
                    <h5 class="row">
                        <b class="col s6">Начален час: <b class="orange-text text-darken-1">@Model.StartTime</b> @Model.Date</b>
                        <b class="col s6">Краен час: <b class="orange-text text-darken-1">@Model.EndTime</b> @Model.Date</b>
                    </h5>

                </p>
            </div>
            <div class="card-action">
                <a asp-controller="Appointment" asp-action="RejectAppointment" asp-route-id="@Model.Id"><b>Отказвам</b></a>
                <a style="border-left:1px solid #fb8c00;height:500px"></a>
                <a asp-controller="Appointment" asp-action="AcceptAppointment" asp-route-id="@Model.Id"><b>Приемам</b></a>
            </div>
        </div>
    </div>
</div>

Вот мои конечные точки:

app.UseEndpoints(
            endpoints =>
                {
                    endpoints.MapControllerRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapRazorPages();
                    endpoints.MapHub<NotificationHub>("/notificationHub");
                });

Примечание: Я использую Microsoft.Extensions.Proxies, так как у меня были некоторые проблемы с загрузкой сущностей в БД и ничего не будет работать даже. Включите, ни Виртуальные свойства.

Я действительно застрял на этом. Заранее спасибо !!

Ответы [ 2 ]

0 голосов
/ 10 апреля 2020

Ссылки - это запросы GET. Вы не можете оставлять сообщения по ссылке, для этого нужны формы. Вам нужно что-то вроде:

<form asp-controller="Appointment" asp-action="AcceptAppointment" asp-route-id="@Model.Id">
    <input type="submit" value="Приемам" />
</form>
0 голосов
/ 10 апреля 2020

Action Link / Anchor elements (a) выдают http GET вызов, поэтому он не может связаться с вашим методом POST.

Если вам нужно сделать запрос POST, вы должны отправить сообщение формы или ajax вызов с методом POST.

...