为什么不允许方法?
Why method isn't allowed?
我为联系表准备了剃须刀组件。 SubmitForm 方法如下所示:
private async Task<string> SubmitForm()
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(ContactFormModel);
var stringContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await Http.PostAsync("/Contact/SendMessage", stringContent);
Logger.LogInformation("Executed PostAsync.");
Debug.Write("Executed PostAsync");
if (response.IsSuccessStatusCode)
{
var resultContent = response.Content.ReadAsStringAsync().Result;
return resultContent;
}
else
return "failed";
}
在第 5 行中,它应该向“/Contact/SendMessage”发送一个 post 请求。
The ContactController looks like:
namespace MannsBlog.Controllers.Web
{
[Route("[controller]")]
public class ContactController : Controller
{
private readonly IMailService _mailService;
private readonly ILogger<ContactController> _logger;
private readonly GoogleCaptchaService _captcha;
public ContactController(IMailService mailService,
ILogger<ContactController> logger,
GoogleCaptchaService captcha)
{
_mailService = mailService;
_logger = logger;
_captcha = captcha;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SendMessage([FromBody] ContactFormModel form)
{
try
{
if (ModelState.IsValid)
{
var spamState = VerifyNoSpam(form);
if (!spamState.Success)
{
_logger.LogError("Spamstate wasn't succeeded");
return BadRequest(new { Reason = spamState.Reason });
}
if (!_captcha.Verify(form.Recaptcha))
{
throw new Exception("The submission failed the spam bot verification.");
}
else
{
_mailService.SendMail("ContactTemplate.txt", form.Name, form.Email, form.Subject, form.Message);
}
return Json(new { success = true, message = "Your message was successfully sent." });
}
_logger.LogError("Modelstate wasnt valid");
return Json(new { success = false, message = "ModelState wasnt valid..." });
}
catch (Exception ex)
{
_logger.LogError("Failed to send email from contact page", ex.Message);
return Json(new { success = false, message = ex.Message });
}
}
}
}
但是如果我执行它,我会收到 RequestMessage 的响应“
RequestMessage {Method: POST, RequestUri:
'https://saschamanns.de/Contact/SendMessage', Version: 1.1, Content:
System.Net.Http.StringContent, Headers: { Request-Context:
appId=cid-v1:64d2a34b-4aea-4d0b-8163-a49082988533 Request-Id:
|fec381c24e685e4b8eddd2b24064a1e4.a6d3a3ff85fe5c44. traceparent:
00-fec381c24e685e4b8eddd2b24064a1e4-a6d3a3ff85fe5c44-00
Content-Type: application/json; charset=utf-8 Content-Length: 572
}} System.Net.Http.HttpRequestMessage"
并作为 ReasonPhrase“方法不允许”。
但是为什么呢?我该如何解决这个问题?
您的 URL 有缺陷。两个选项:
Use Http.PostAsync("/Contact", stringContent); //no /SendMessage
或
- 在控制器中,使用
[HttpPost("SendMessage")]
以及来自 codereview 的一些不相关的建议:
- 不要使用
.Result
:
//var resultContent = response.Content.ReadAsStringAsync().Result;
var resultContent = await response.Content.ReadAsStringAsync();
考虑 System.Text.Json
而不是 Newtonsoft。
当您使用 Http.PostAsJsonAsync(...)
时,您可以一次性解决这两个问题。
我为联系表准备了剃须刀组件。 SubmitForm 方法如下所示:
private async Task<string> SubmitForm()
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(ContactFormModel);
var stringContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await Http.PostAsync("/Contact/SendMessage", stringContent);
Logger.LogInformation("Executed PostAsync.");
Debug.Write("Executed PostAsync");
if (response.IsSuccessStatusCode)
{
var resultContent = response.Content.ReadAsStringAsync().Result;
return resultContent;
}
else
return "failed";
}
在第 5 行中,它应该向“/Contact/SendMessage”发送一个 post 请求。
The ContactController looks like:
namespace MannsBlog.Controllers.Web
{
[Route("[controller]")]
public class ContactController : Controller
{
private readonly IMailService _mailService;
private readonly ILogger<ContactController> _logger;
private readonly GoogleCaptchaService _captcha;
public ContactController(IMailService mailService,
ILogger<ContactController> logger,
GoogleCaptchaService captcha)
{
_mailService = mailService;
_logger = logger;
_captcha = captcha;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SendMessage([FromBody] ContactFormModel form)
{
try
{
if (ModelState.IsValid)
{
var spamState = VerifyNoSpam(form);
if (!spamState.Success)
{
_logger.LogError("Spamstate wasn't succeeded");
return BadRequest(new { Reason = spamState.Reason });
}
if (!_captcha.Verify(form.Recaptcha))
{
throw new Exception("The submission failed the spam bot verification.");
}
else
{
_mailService.SendMail("ContactTemplate.txt", form.Name, form.Email, form.Subject, form.Message);
}
return Json(new { success = true, message = "Your message was successfully sent." });
}
_logger.LogError("Modelstate wasnt valid");
return Json(new { success = false, message = "ModelState wasnt valid..." });
}
catch (Exception ex)
{
_logger.LogError("Failed to send email from contact page", ex.Message);
return Json(new { success = false, message = ex.Message });
}
}
}
}
但是如果我执行它,我会收到 RequestMessage 的响应“
RequestMessage {Method: POST, RequestUri: 'https://saschamanns.de/Contact/SendMessage', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Request-Context: appId=cid-v1:64d2a34b-4aea-4d0b-8163-a49082988533 Request-Id: |fec381c24e685e4b8eddd2b24064a1e4.a6d3a3ff85fe5c44. traceparent: 00-fec381c24e685e4b8eddd2b24064a1e4-a6d3a3ff85fe5c44-00
Content-Type: application/json; charset=utf-8 Content-Length: 572 }} System.Net.Http.HttpRequestMessage"
并作为 ReasonPhrase“方法不允许”。
但是为什么呢?我该如何解决这个问题?
您的 URL 有缺陷。两个选项:
Use Http.PostAsync("/Contact", stringContent); //no /SendMessage
或
- 在控制器中,使用
[HttpPost("SendMessage")]
以及来自 codereview 的一些不相关的建议:
- 不要使用
.Result
:
//var resultContent = response.Content.ReadAsStringAsync().Result;
var resultContent = await response.Content.ReadAsStringAsync();
考虑
System.Text.Json
而不是 Newtonsoft。当您使用
Http.PostAsJsonAsync(...)
时,您可以一次性解决这两个问题。