Метод не разрешен 405 POST ASP.NET CORE 5.0 WEB APIC#

Место общения программистов C#
Anonymous
Метод не разрешен 405 POST ASP.NET CORE 5.0 WEB API

Сообщение Anonymous »

Я запускаю два проекта одновременно в своем проекте MVC, когда я вызываю метод PaymentServiceAsync(), когда он достигает строки ответа.EnsureSuccessStatusCode() это переменная ответ code> говорит Метод не разрешен (405) Кажется, я не могу понять, почему он это делает, если он установлен правильно.
Вот мой Метод PaymentServiceAsync():
public async Task PaymentServiceAsync()
{
var response = await _httpClient.GetAsync("api/paymentservices/payment");

response.EnsureSuccessStatusCode();

var result = await response.Content.ReadAsStringAsync();

return result;
}

Теперь в моем проекте основного веб-API asp.net это мой контроллер, который он вызывает:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nest;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using PaymentService.API.Models;
using Microsoft.Extensions.Logging;

namespace PaymentService.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PaymentServicesController : ControllerBase
{
private String _connectionString;
private IElasticClient _elasticClient = new ElasticClient();
private readonly ILogger
_logger;

public PaymentServicesController(IConfiguration configuration, ILogger logger)
{
_connectionString = configuration.GetConnectionString("Default");
_logger = logger;
}

// POST api/
[HttpPost]
[Route("payment")]
public async Task Post([FromBody] string value)
{
_logger.LogInformation("Payment method involked!");
using (SqlConnection connection = new SqlConnection(_connectionString))
{
Console.WriteLine("\nOpening connection...");

SqlCommand command = new SqlCommand("insert into applog(ElkLog_id, CorrelationId, DateCreated, MessageTemplate, Message) values(@elk_id, @cid, @dt, @mt, @m)", connection);

string indexName = "customer-simulation-es-app-logs*";
var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"));
connectionSettings.DefaultIndex(indexName);
connectionSettings.EnableDebugMode();
_elasticClient = new ElasticClient(connectionSettings);

// this will tell us how much hits/results there is based on the following criteria
var countResponse = _elasticClient.Count(c => c
.Query(q => q
.Bool(b => b
.Should(
m => m
.Match(ma => ma
.Field(fa => fa.level)
.Query("Error")),
m => m
.Match(ma => ma
.Field(fa => fa.level)
.Query("Information")))
.Filter(f => f.DateRange(dr => dr
.Field("@timestamp")
.GreaterThanOrEquals("2021-06-18T16:34:45.701-05:00")
.LessThanOrEquals("2021-07-18T16:34:45.701-05:00")))
.MinimumShouldMatch(1)))).Count;

Console.WriteLine($"\nDocuments in index: {countResponse}");

Console.WriteLine($"Open new pit");
var openPit = await _elasticClient.OpenPointInTimeAsync(indexName, d => d.KeepAlive("1m"));
var pit = openPit.Id;

Console.WriteLine($"Read all docs from index ..");
// we will start reading docs from the beginning
var searchAfter = DateTimeOffset.MinValue;

var elkLogId = "";
var correlationId = "";
var dateCreated = default(DateTimeOffset);
var messageTemplate = "";
var message = "";
int numrows = 0;

try
{
connection.Open();

Console.WriteLine("\nConnection successful!");

while (true)
{
........

numrows = await command.ExecuteNonQueryAsync();

command.Parameters.Clear();

}

Console.WriteLine("\nAll logs have been recorded to the database successfully!");

connection.Close();
Console.WriteLine("\nConnection closed....");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine($"Close pit");
var closePit = await _elasticClient.ClosePointInTimeAsync(d => d.Id(pit));
}

return numrows;
}
}

}
}

appsettings.json
{
"ConnectionStrings": {
"Default": "Data Source=.\\SQLExpress;Database=ElasticSearchService;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}


Подробнее здесь: https://stackoverflow.com/questions/684 ... -0-web-api

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