Http error 405: Получить запрос вместо публикации в C#/. Net Web App с AWS SNS и интеграцией DynamoDBC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Http error 405: Получить запрос вместо публикации в C#/. Net Web App с AWS SNS и интеграцией DynamoDB

Сообщение Anonymous »

У меня есть сетевое веб -приложение C#/. размещено на AWS. Я пытаюсь добавить функцию, в которой клиент вводит свой номер телефона, и на него отправляется бесплатный продукт. Я использую AWS SNS и DynamoDB. Я тестирую это на местном хосте. Код, который я написал ниже.[HttpPost] // Ensures this action is for POST requests**
[Route("Home/FreeCoffee")]
public async Task FreeCoffee([FromBody] PhoneNumberRequest request)
{
if (string.IsNullOrEmpty(request.PhoneNumber))
{
return BadRequest(new { message = "Phone number is required." });
}

string dateKey = DateTime.UtcNow.ToString("yyyy-MM-dd") + "_Free1";

// Check if the offer already exists for this user today
var existingOffer = await _db.LoadAsync(request.PhoneNumber, dateKey);

if (existingOffer != null)
{
return Ok(new { message = $"Offer already issued: {existingOffer.Code}" });
}

// Generate new offer code
var newCode = GenerateOfferCode();
var offer = new OfferCode
{
PhoneNumber = request.PhoneNumber,
OfferDateOfferType = dateKey,
Code = newCode,
OfferType = "Free1",
Used = false,
ExpirationDate = DateTimeOffset.UtcNow.AddHours(24).ToUnixTimeSeconds() // Expires in 24 hours
};

// Save to DynamoDB
await _db.SaveAsync(offer);

// Send SMS via SNS
var message = $"Your offer code is: {newCode}. Use it before midnight!";
await _snsClient.PublishAsync(new PublishRequest
{
Message = message,
PhoneNumber = request.PhoneNumber
});

return Ok(new { message = $"Offer sent to {request.PhoneNumber}" });
}
< /code>


Submit

< /code>

document.getElementById("codeForm").addEventListener("submit", async function (event) {
event.preventDefault(); // Prevent form from making a GET request

const phoneNumber = document.getElementById("phoneNumber").value;
if (!phoneNumber) {
alert("Phone number is required!");
return;
}

try {
const response = await fetch('/Home/FreeCoffee', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ phoneNumber: phoneNumber })
});

if (!response.ok) {
const result = await response.json();
alert("Error: " + result.message);
} else {
const result = await response.json();
alert("Offer sent to: " + phoneNumber);
}
} catch (error) {
alert("Error: " + error.message);
}
});
< /code>
The error I am getting is HTTP error 405. I have checked the developer tools network tab and found this:
Request Method: GET
Status Code:
405 Method Not Allowed
Remote Address:
[::1]:5043
Referrer Policy:
strict-origin-when-cross-origin
allow: POST
content-length: 0
date: Wed, 19 Mar 2025 23:25:07 GMT
server: Kestrel
< /code>
If I am understanding this correctly, I am using a GET request but a POST request is expected. I have been trying to remedy this, without success. Can anyone see what I am doing wrong? I would appreciate any help.
Edited content to show the potential source of the Get/Post problem

[*]

Offers
  • Coffee
  • Cookie


Подробнее здесь: https://stackoverflow.com/questions/795 ... ws-sns-and
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»