Web API Post 错误 - HTTP 错误 405.0 - 方法不允许

Web API Post error - HTTP Error 405.0 - Method Not Allowed

这是我的 UI,它使用 ajax 到 post 数据到网络 api。

<form id="myForm" method="post">
    Username <input name="Email" id="Email" type="text" /> <br />
    Password <input name="Password" id="Password" type="text" /> <br />
    Confirm Password <input name="ConfirmPassword" id="ConfirmPassword" type="text" /> <br />
    <input id="btnRegister" type="submit" value="Register" />
</form>

<script>
$(function () {
    $('#btnRegister').click(function () {
        debugger
        var sForm = $('#myForm').serialize();

        $.ajax({
            type: 'POST',
            url: 'https://localhost:44358/api/Account/Register',
            contentType: "application/json",
            dataType: "json",
            data: sForm,
            success: function () {
                alert('Success');
            },
            error: function (xhr, status, error) {

            }
        })
    })
})
</script>

在我的网站API,我有这个操作方法。

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

使用 Postman,我已经测试过它并且有效。我可以插入数据库,但如果我从 html.

发送它,我会遇到上述错误

我的 RegisterBindingModel:

 public class RegisterBindingModel
{
    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

在同一项目中添加了另一个普通控制器进行测试。它通过了 ModelState 但挂在粗体行。

[HttpPost]
    public ActionResult Register(RegisterBindingModel registerBindingModel)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }
        using (var client = new HttpClient())
        {

            **HttpResponseMessage responsePost = GlobalVariables.WebApiClient.PostAsJsonAsync("Account/Register", registerBindingModel).Result;**
            if (responsePost.IsSuccessStatusCode)
            {
                // Get the URI of the created resource.
                Uri returnUrl = responsePost.Headers.Location;
                if (returnUrl != null)
                {
                    ViewBag.Message = "Added";
                }

            }
            else
            {
                ViewBag.Message = "Internal server Error: " + responsePost.ReasonPhrase;

            }
        }
        return View();
    }

全局变量:

public class GlobalVariables
{
    public static HttpClient WebApiClient = new HttpClient();

    static GlobalVariables()
    {
        WebApiClient.BaseAddress = new Uri("http://localhost:44358/api/");         
        WebApiClient.DefaultRequestHeaders.Clear();
        WebApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
}

有人可以在这里提供一些线索吗?

不允许的方法是当您尝试执行 post、get 等

在您的端点上添加标签 [HttpPost]

// POST api/Account/Register
[AllowAnonymous]
[HttpPost]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

    if (!result.Succeeded)
    {
        return GetErrorResult(result);
    }

    return Ok();
}

发生这种情况是因为最初没有遵循默认路由约定,但在您更正了基础 url 之后,API 开始工作。根据规格:

In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives a request, it routes the request to an action.

为了确定调用哪个操作,框架使用了路由 table。 Web API 的 Visual Studio 项目模板创建默认路由:

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

因此,当您需要调用您的 API 时,您的基础 url 应该有 /api