首页 > 解决方案 > Asp.Net Core 3.1 405 方法不允许

问题描述

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

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

这是我的控制器

[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());
    }

这是 URL 的示例图像和结果

标签: c#asp.net-core-webapi

解决方案


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

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


推荐阅读