c# - 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"));
}
}
任何人都可以在这里提供一些线索吗?
解决方案
不允许的方法是当您尝试发帖、获取等时。
[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();
}
推荐阅读
- css - 如何在 Vuetify 数据表中显示所有项目而不是仅显示 10 行?
- google-cloud-platform - 出于安全原因,此 URL 只能使用 localhost (127.0.0.1) 作为主机名访问
- azure - 如何从服务总线死信队列中读取消息?
- quill - 单击按钮时如何触发 Quill JS 的提及模块
- ruby-on-rails - 自定义引导变量不适用于 Rails 6 和 Webpacker
- java - 如何在android studio java中向textview指定问题?
- python-3.x - Huggingface 的变形金刚管道
- symfony - 为 API Platform Bundle 中的布尔过滤器设置标准过滤器值
- python - 高斯混合模型的代码是否正确?
- node.js - 在 mongodb 文档中更新不起作用