【问题标题】:ASP.NET Core HTTP Error 405 - Bad Method when routing to post controller actionASP.NET Core HTTP 错误 405 - 路由到后控制器操作时的错误方法
【发布时间】:2020-07-22 16:28:43
【问题描述】:

所以我有一个 AppointmentController,它有一个动作 AcceptAppointment。方法应该是 POST。但是每次我单击 Razor 页面中的 ActionLink 时,都会出现以下错误。 此页面无法正常工作如果问题仍然存在,请与网站所有者联系。 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 视图:

@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,因为我在使用数据库时遇到了一些实体加载问题,甚至 .Include 和 Virtual 属性都无法正常工作。

我真的坚持这个。提前致谢!!

【问题讨论】:

  • 人们经常遇到代理设置问题。让代码运行几分钟,看看它是否有效。如果代理不可用,代码会等待 30 秒以使代理超时,然后尝试不使用代理。因此,在我们尝试其他方法之前,让我们看看代码是否在几分钟后完成。

标签: c# asp.net-mvc asp.net-core routes http-status-code-405


【解决方案1】:

Action Links/Anchor 元素 (a) 发出一个 http GET 调用,这就是它无法访问您的 POST 方法的原因。

如果您需要发出 POST 请求,则必须发出表单 post 或使用 POST 方法的 ajax 调用。

【讨论】:

  • 谢谢你们俩。愚蠢的错误。顺便说一句,如果我继续使用 Microsoft.Extension.Proxies 进行延迟加载是否可以,或者它是否有缺陷。我只是无法在需要时填充数据库中的任何相关集合。例如,我有一个带有许多通知的 Dogsitter,但是当我调用虚拟集合时它是空的。
  • 嗨@DrinkBlink,您可以参考official docs
【解决方案2】:

链接是 GET 请求。您不能通过链接发布;这就是表格的用途。你需要类似的东西:

<form asp-controller="Appointment" asp-action="AcceptAppointment" asp-route-id="@Model.Id">
    <input type="submit" value="Приемам" />
</form>

【讨论】:

    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 2014-10-21
    • 2018-12-19
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多