c# - 无法使用 GET 访问 API 端点

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

我正在构建一个 API 来处理 .NET Core 中的身份信息,但每次我尝试调用电话时都会收到 404。

当我环顾四周寻找答案时,似乎没有任何明确的地方,因为发布的代码似乎很少。以下是我认为相关的所有内容。

Controller :

using Common.Extensions;
using Identity.Database.Contexts.Models;
using Identity.WebApi.Models;
using Identity.WebApi.Models.Tokens;
using Identity.WebApi.Services.Access;
using Identity.WebApi.Services.Accounts;
using Identity.WebApi.Services.Tokens;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

using Controller = Microsoft.AspNetCore.Mvc.Controller;
using Get = Microsoft.AspNetCore.Mvc.HttpGetAttribute;
using Post = Microsoft.AspNetCore.Mvc.HttpPostAttribute;
using Route = Microsoft.AspNetCore.Mvc.RouteAttribute;

namespace Identity.WebApi.Controllers
{
    [Route("api/[controller]")]
    public class IdentityController : Controller
    {
        private readonly IApplicationUserService _userService;
        private readonly IAccessService _accessService;
        private readonly ITokenService _tokenService;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public IdentityController(IApplicationUserService userService, IAccessService accessService, ITokenService tokenService, SignInManager<ApplicationUser> signInManager)
        {
            _userService = userService;
            _accessService = accessService;
            _tokenService = tokenService;
            _signInManager = signInManager;
        }

        [Get]
        [AllowAnonymous]
        public string Index()
        {
            return new Dictionary<string,string>
            {
                { "status", "live" }
            }.Serialize();
        }

        [Post]
        [Route("create")]
        [AllowAnonymous]
        public Task<ISet<IdentityResult>> Create(string user)
        {
            var decodedUser = DecodeUser(user);

            var applicationUser = new ApplicationUser(new User
            {
                Id = Guid.NewGuid(),
                Name = decodedUser.Username,
                LastActive = DateTime.UtcNow
            });

            return _userService.Add(applicationUser, decodedUser.Password);
        }       

        private (string Username, string Password) DecodeUser(string encodedUser)
        {
            var decodedUser = encodedUser.DecodeFrom64().Split(':');
            return (Username: decodedUser[0], Password: decodedUser[1]);
        }

        private async Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
            => await _signInManager.UserManager.CheckPasswordAsync(user, password);
    }
}

创业公司:

using Identity.Database.Contexts;
using Identity.Database.Contexts.Access;
using Identity.Database.Contexts.Extensions;
using Identity.Database.Contexts.Models;
using Identity.WebApi.Models;
using Identity.WebApi.Services.Access;
using Identity.WebApi.Services.Accounts;
using Identity.WebApi.Services.Certs;
using Identity.WebApi.Services.Tokens;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Runtime.CompilerServices;

namespace Identity.WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new CertService(Configuration) as ICertService)
                .AddTransient<IApplicationUserService, ApplicationUserService>()
                .AddTransient<IApplicationRoleService, ApplicationRoleService>()
                .AddTransient<IAccessService, AccessService>()
                .AddTransient<ICertService, CertService>()
                .AddTransient<ITokenService, TokenService>()
                .AddTransient<ICrudDao<AppDbContext, Role>, RoleDao>()
                .AddIdentities<ApplicationUser, ApplicationRole>()
                .AddScoped<UserManager<ApplicationUser>, UserManager<ApplicationUser>>()
                .AddScoped<SignInManager<ApplicationUser>, SignInManager<ApplicationUser>>()
                .AddScoped<RoleManager<ApplicationRole>, RoleManager<ApplicationRole>>()
            .AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.Use(async (c, n) =>
            {
                await n();

                if (c.Response.StatusCode == 404)
                {
                    c.Request.Path = "/identity";
                    await n();
                }
            });

            app.UseStaticFiles();
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc(r => { r.MapRoute(name: "default", template: "{controller=identity}/{action=Index}"); });
        }
    }
}

启动设置:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:55048/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/identity/index",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApplication1": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/identity/index",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:55048/"
    }
  }
}

最佳答案

在你的 Controller 的顶部,你有:

[Route("api/[controller]")]
public class IdentityController : Controller

这意味着如果您的路由仅以 api/ 开头,那么它将匹配 Controller 。此外,您的 Index 操作没有任何额外的路由属性,因此它仅查找 api/identity 。但是,您的启动设置与该部分不匹配,并且由于您没有任何其他路由匹配它,您会收到 404。

由于这个原因,app.UseMvc 中的默认路由将不起作用。

简单修复:在您的启动设置中将launchUrl 更改为api/identity...然后按照@Nkosi 的answer 进行操作

关于c# - 无法使用 GET 访问 API 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573128/

相关文章:

c# - 如何将 slug 添加到 asp.net 核心网站中的所有链接生成?

c# - 手动调用事件处理程序

c# - 模棱两可的类名

c# - 用子弹射击时物体不会被摧毁 - UNITY3D C#

c# - 如何在 oData .Net core 3.1 中启用 $levels

c# - 数十次调用后应用程序服务 502 网关错误

c# - 如何在 .NET Core 3.1 应用程序中添加 WCF 服务引用?

c# - EF 在数据库中创建关系 id 列,该列不是模型的一部分

c# - mvc 6 只生成一次 antiforgerytoken

c# - sql中不能减