为什么此ASP.NET Core POST请求返回“ 405(不允许使用方法)”?

克雷登

我有一个使用ASP.NET Core 2.1创建的非常简单的API。当客户端页面从localhost:8080调用API时,位于localhost:5000的API返回HTTP:405。

为什么?请注意,AuthController.cs中的HTTP GET测试方法可以按预期工作。这只是返回HTTP:405的HTTP POST请求。

控制器\ AuthController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using server.Models;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;

namespace server.Controllers
{
    [Route("api/auth")]
    [ApiController]
    public class AuthController : ControllerBase
    {

        [HttpGet, Route("test")]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpPost, Route("login")]
        public IActionResult Login([FromBody]LoginModel user)
        {
            if (user == null)
            {
                return BadRequest("Invalid client request");
            }

            if (user.UserName == "johndoe" && user.Password == "def@123")
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:5000",
                    audience: "http://localhost:5000",
                    claims: new List<Claim>(),
                    expires: DateTime.Now.AddMinutes(10),
                    signingCredentials: signinCredentials
                );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                return Ok(new { Token = tokenString });
            }
            else
            {
                return Unauthorized();
            }
        }
    }
}

型号\ LoginModel.cs

namespace server.Models
{
    public class LoginModel
    {
        public string UserName { get; set;}
        public string Password { get; set; }
    } 
}

启动文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Cors.Infrastructure;

namespace server
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer = "http://localhost:5000",
                    ValidAudience = "http://localhost:5000",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
                };
            });

            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.WithOrigins("http://localhost:8080");
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

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

            app.UseCors("SiteCorsPolicy");
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

index.html(localhost:8080)

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>JWT Auth</title>
    </head>
    <body>
        <p>Output:</p>
        <div id="output"></div>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script>

            var item =  {
                UserName: "johndoe",
                Password: "def@123" 
            };

            $.ajax({
                type: "POST",
                accepts: "application/json",
                url: '/api/auth/Login',
                contentType: "application/json",
                data: JSON.stringify(item),
                error: function(jqXHR, textStatus, errorThrown) {
                alert("Something went wrong!");
                },
                success: function(result) {
                    console.log('Testing');
                }
            });

        </script>
    </body>
</html>
米尔科

看起来您正在发布到/ api / auth / login,但是在服务器上托管页面的主机(即localhost:8080)。您是要发布到http:// localhost:5000 / api / auth / login吗?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当不允许使用方法时,ASP.NET Core返回自定义响应

方法不允许 405 POST ASP.NET CORE 5.0 WEB API

ASP.NET Core句柄方法不允许405

不允许使用ASP.NET Core 2.2 WebAPI 405方法

当我在ASP.NET WebAPI CORS中发送POST数据时,HTTP CODE 405(不允许使用方法)

ASP.NET WebApi:不允许使用(405)方法

405在ASP.NET Web API控制器中不允许使用方法选项?

带有ASP.NET Core 2.1和UWP应用的SignalR Webhost作为客户端返回“不允许的405方法”

getRefreshInfo返回405(不允许使用方法)

运行测试时,无法在ASP.NET Core中调用API DELETE(不允许使用405方法)。但是它会招摇

ASP.NET和jQuery无法加载资源:服务器的响应状态为405(不允许使用方法)

ASP.NET 5 WebApi OPTIONS 预检中不允许使用 405 方法

尝试发布AJAX请求时的POST 405(不允许使用方法)-Laravel 4

不允许使用方法“ POST”

角度:HTTP GET请求-选项405(不允许使用方法)

csrf-token POST 405(不允许使用方法)Laravel

c#-405(不允许使用方法)从Angular 2应用进行POST时

Ajax POST结果为405(不允许使用方法)-Spring MVC

.NET Core 2.2 CORS不允许请求

NGINX返回405不允许使用POST方法

配置方法中的ASP Net Core请求服务返回null

405方法不允许-ASP.NET Web API

ASP.NET Core:为什么在POST请求期间我们为什么必须使用FromBodyAttribute从JSON负载中混合参数?

405不允许使用方法http方法:spring-security中不支持请求方法'GET'

ASP.NET Core API Controller即使成功完成POST请求也不会返回任何内容

405错误:请求的网址不允许使用该方法

为什么我的ASP.NET Core 2方法不能返回TwiML?

405不允许用于POST的方法

不允许ExpressJS 405 POST方法