我為我的聯系表格準備了一個剃須刀組件。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 {方法:POST,RequestUri:'https://saschamanns.de/Contact/SendMessage',版本:1.1,內容:System.Net.Http.StringContent,標題:{請求背景關系:appId=cid-v1:64d2a34b -4aea-4d0b-8163-a49082988533 請求 ID:|fec381c24e685e4b8eddd2b24064a1e4.a6d3a3ff85fe5c44。traceparent:00-fec381c24e685e4b8eddd2b24064a1e4-a6d3a3ff85fe5c44-00
內容型別:應用程式/json;charset=utf-8 內容長度:572 }} System.Net.Http.HttpRequestMessage"
并作為 ReasonPhrase “不允許的方法”。
但為什么?我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
你的網址有問題。兩種選擇:
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(...)一次性解決這兩個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382023.html
標籤:网站 剃刀 西装外套 httpweb请求 .net-5
下一篇:當私有建構式有引數時創建單例
