首页 > 解决方案 > Web API 发布错误 - HTTP 错误 405.0 - 方法不允许

问题描述

这是我的 UI,它使用 ajax 将数据发布到 web 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>

在我的 Web 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 发送它,我会遇到上述错误。

我的注册绑定模型:

 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"));
    }
}

任何人都可以在这里提供一些线索吗?

标签: c#restapihttpasp.net-ajax

解决方案


不允许的方法是当您尝试发帖、获取等时。

[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();
}

推荐阅读