c# - 不允许使用 Asp.Net Core 3.1 405 方法

标签 c# asp.net-core-webapi

嗨,伙计们,我需要帮助.. 我总是得到 405 Method Not Allowed

我正在使用 Asp.Net Core Web Application 3.1,我对 HttpGet 没有问题,但是当我使用 HttpPost 时,它总是返回 405 状态代码

这是我的 Controller

[Route("api/[controller]")]
[ApiController]
public class ExamController : ControllerBase
{
    [HttpPost("PostValue")]
    public ActionResult<HttpResponseMessage> PostInfo([FromBody] PersonalInfo info)
    {
        string json = JsonConvert.SerializeObject(info);
        HttpClient client = new HttpClient();
        var response = client.PostAsync("https://sampleapi/receive", new StringContent(json, Encoding.UTF8, "application/json"));

        if (response.IsFaulted)
            return BadRequest(response);

        return Ok(response);
    }
}

这是我的创业类
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStatusCodePages();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseCors(options => options.AllowAnyOrigin());
    }

Here is the sample image of URL and the Result

最佳答案

查看提供的图像,您使用 chrome 发出 url 请求,这是一个 HTTP GET 命令。因此,您的应用程序获得了一个 HTTP GET 命令,但您的方法想要接受一个 HTTP POST 方法。这就是为什么它说“方法不允许”。

如果你想尝试http命令,你需要一个web测试工具,比如PostMan .

关于c# - 不允许使用 Asp.Net Core 3.1 405 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60850457/

相关文章:

c# - 在 C# 中设置电子邮件附件名称

c# - .Net 6 System.IO.Compression 问题是否有任何解决方法。 DeflateStream.Read 方法在 .Net 6 中工作不正确,但在旧版本中工作正常

asp.net-core - 应用程序中断访问 dbcontext、Asp .net 核心 web api 2.0 与 Entity Framework 核心 2.0 数据库第一种方法

azure - 禁用Azure应用服务的CORS中间件

c# - Microsoft.AspNetCore.Odata 配置日期时间序列化以使用 Utc 或省略 Timezone

c# 泛型重载方法分派(dispatch)不明确

c# - 构造函数中的数据验证

c# - 私有(private)服务器/客户端的自签名证书安全

c# - 调用 MySql 存储过程,它从 asp.net core 2.2 web API Controller 获取 2 个参数

c# - .net core 2 API 中是否真的需要 services.AddSingleton<IConfiguration>