标签: asp.net-core-webapi

读取请求正文两次

我试图在中间件中读取正文以进行身份​​验证,但是当请求到达api控制器时,对象是空的,因为正在读取正文.有没有办法解决.我正在中间件中读这样的身体.

var buffer = new byte[ Convert.ToInt32( context.Request.ContentLength ) ];
await context.Request.Body.ReadAsync( buffer, 0, buffer.Length );
var body = Encoding.UTF8.GetString( buffer );
Run Code Online (Sandbox Code Playgroud)

asp.net-core-mvc asp.net-core asp.net-core-webapi

19
推荐指数
2
解决办法
1万
查看次数

WebAPI核心路由问题

所以,我正在使用Web API(ASP.NET Core 2)并遇到路由问题.

我有几个控制器,如:

SchoolController
TeacherController.

两者都有获取: Get(int id)

问题是当我运行它时,我甚至在实际能够调用方法之前就会遇到运行时错误.

Attribute routes with the same name 'Get' must have the same template:
Action: MyProject.WebAPI.Controllers.SchoolController.Get (MyProject.WebAPI)' - Template: 'api/school/{id}'
Action: MyProject.WebAPI.Controllers.TeacherController.Get (MyProject.WebAPI)' - Template: 'api/teacher/{id}'
Run Code Online (Sandbox Code Playgroud)

当控制器应该拥有自己的Get等时,为什么会这样做...所以你可以这样做:

/api/{controller}/1

etc... ?
Run Code Online (Sandbox Code Playgroud)

现在,我还有另一个Get方法,它们都在它们的控制器中但具有不同的方法签名以及不同的HttpGet名称,即:

// TeachersController:

[Produces("application/json")]
[Route("api/teacher")]
public class TeacherController : Controller
{

    // GET: api/Teacher/5
    [HttpGet("{id}", Name = "Get")]
    public IActionResult Get(int id)
    {

        // BLAH
    }
}
Run Code Online (Sandbox Code Playgroud)

并为学校控制员:

[Produces("application/json")]
[Route("api/school")]
public class SchoolController : Controller
{

    [HttpGet("{id}", Name = "Get")]
    public …
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core asp.net-core-webapi asp.net-core-routing

19
推荐指数
2
解决办法
1万
查看次数

System.NotSupportedException:不支持“System.Action”实例的序列化和反序列化。路径:$.MoveNextAction

我正在遵循有关 .NET 6 的简单教程,它应该工作起来非常简单,但显然我遇到了异常。示例代码如下:

public async Task<ServiceResponse<List<GetCharacterDto>>> GetAllCharacters()
{
    var response = new ServiceResponse<List<GetCharacterDto>>();
    var dbCharacters = await _context.Characters.ToListAsync();
    response.Data = dbCharacters.Select(c => _mapper.Map<GetCharacterDto>(c)).ToList();

    return response;
}
Run Code Online (Sandbox Code Playgroud)

GetCharacterDto中的代码是:

public class GetCharacterDto
{ 
    public int Id { get; set; }
    
    public string Name { get; set; } = "Frodo";

    public int HitPoints { get; set; } = 100;

    public int Strength { get; set; } = 10;

    public int Defense { get; set; } = 10;

    public int Intelligence { get; …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core asp.net-core-webapi .net-6.0

19
推荐指数
1
解决办法
3万
查看次数

获取范围使用asp.net核心中的JavaScript客户端验证Identity Server 4中的错误

从我的Javascript客户端应用程序向我的Identity Server应用程序发出请求时,我收到以下错误.

fail:IdentityServer4.Validation.ScopeValidator [0] 无效范围:openid

我已确保在Identity Server应用程序中添加范围.以下是我的代码.

IdentityServer应用程序(主机) Config.cs

  public class Config
{
    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1","My API")
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                 ClientId = "js",
                 ClientName = "javaScript Client",
                 AllowedGrantTypes = GrantTypes.Implicit,
                 AllowAccessTokensViaBrowser = true,
                 RedirectUris = { "http://localhost:5003/callback.html" },
                 PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
                 AllowedCorsOrigins = { "http://localhost:5003" },
                 AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api1"
                    }
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs

  public …
Run Code Online (Sandbox Code Playgroud)

c# oauth-2.0 openid-connect identityserver4 asp.net-core-webapi

18
推荐指数
1
解决办法
2万
查看次数

使用JWT的.Net Core 2.0 Web API - 添加标识会破坏JWT身份验证

(编辑 - 找到正确的解决方案!见下文)

好的 - 这是我第一次尝试使用.Net Core 2.0和身份验证,虽然我过去曾使用过Web API 2.0,并且在过去几年中对各种MVC和Webforms ASP项目进行了相当广泛的工作.

我正在尝试使用.Net Core创建一个仅限Web API的项目.这将形成多租户应用程序的后端以生成一些报告,因此我需要能够对用户进行身份验证.通常的方法是使用JWT - 首先验证用户生成令牌,然后将其传递给客户端以在每个API请求上使用.将使用EF Core存储和检索数据.

我按照这篇文章找到了这个设置的基本方法,我设法让它工作正常 - 我有一个接受用户名/密码的控制器并返回一个令牌(如果有效),并且一些授权策略设置基于索赔.

我需要的下一件事是实际管理用户/密码/等.我以为我只是使用.Net核心身份,因为我会有很多现成的代码来担心用户/角色,密码等.我使用的是自定义User类和UserRole派生自标准IdentityUserIdentityRole类的类,但我现在已经恢复到标准的那个.

我遇到的问题是我无法弄清楚如何添加身份并注册所有各种服务(rolemanager,usermanager等)而不会破坏身份验证 - 基本上只要我将此行添加到我的Startup.ConfigureServices类中:

services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<MyContext>();
Run Code Online (Sandbox Code Playgroud)

这一切都出错了,当我收到请求时,我再也看不到任何索赔,所以所有的政策都锁定了,你无法得到任何东西.

如果我没有那些行,那么我最终会遇到与UserManager,RoleManager,UserStore等相关的错误.所有这些都没有注册DI.

那么......如何(如果可能的话)我可以注册身份并正确地将其连接到上下文,但是避免/删除对实际授权机制的任何更改?

我已经在网上看了很多,但是自从.Net Core 1.x以来已经发生了很多变化,所以很多教程等都不再有效了.

我不打算让这个API应用程序拥有任何前端代码,因此我现在不需要对表单或任何内容进行任何cookie身份验证.

编辑
确定,我现在发现在此代码中设置Startup.ConfigureServices()方法中的JWT身份验证:

 services.AddAuthentication(
            JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                 >>breakpoint>>>   options.TokenValidationParameters =
                        new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,

                            ValidIssuer = "Blah.Blah.Bearer",
                            ValidAudience = "Blah.Blah.Bearer",
                            IssuerSigningKey …
Run Code Online (Sandbox Code Playgroud)

jwt asp.net-identity-2 asp.net-core-webapi

18
推荐指数
1
解决办法
5454
查看次数

动作需要 Swagger 的独特方法/路径组合

HTTP GET在同一个控制器中有 2 个方法并给我这个错误

HTTP 方法“GET”和路径“api/DataStore”被动作重载 - DPK.HostApi.Controllers.DataStoreController.GetByIdAsync (DPK.HostApi),DPK.HostApi.Controllers.DataStoreController.GetAllAsync (DPK.HostApi)。操作需要 Swagger 2.0 的唯一方法/路径组合。

我的控制器:

[Route("api/[controller]")]
[ApiController]
public class DataStoreController : ApiControllerBase
{
    private readonly IDataStoreService _dataStoreService;

    public DataStoreController(IDataStoreService dataStoreService)
    {
        _dataStoreService = dataStoreService;
    }


    [HttpPost]
    public async Task<IActionResult> PostAsync([FromBody] DataStoreCommand dataStoreCommand)
    {
        try
        {
            if (ModelState.IsValid)
            {
                await _dataStoreService.PostAsync(dataStoreCommand);
                return Ok();
            }

            var errorList = ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList();
            return ValidationProblem();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }


    [HttpPut]
    public async Task<IActionResult> PutAsync([FromBody] DataStoreCommand dataStoreCommand) …
Run Code Online (Sandbox Code Playgroud)

c# swagger swagger-ui asp.net-core asp.net-core-webapi

18
推荐指数
5
解决办法
2万
查看次数

每当我发送包含不记名令牌的请求时,ASP.Net Core API 总是返回未经授权的 401

我有一个 ASP .NET Core web api,我生成了一个用于授权目的的 JWT 令牌,但是每当我使用带有 Bearer 令牌标头的 Postman 发出请求时,我都会得到 401 Unauthorized。当我从使用 API 的前端尝试时也是如此。当我删除授权时一切正常

尝试将标题中的授权更改为 //[Authorize(AuthenticationSchemes = "Bearer")] 也转到 jwt.io 以确保 JWT 令牌有效。

//function where I generate JWT
  public   User AuthenticateAdmin(string username, string password)
        {
            var user =  _context.User.FirstOrDefault(x => x.UserName == username && x.Password == password);

            //return null if user is not found 
            if  (user == null) return null;

            //authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = …
Run Code Online (Sandbox Code Playgroud)

c# authorization unauthorized asp.net-core-webapi

18
推荐指数
4
解决办法
2万
查看次数

ASP.NET Core Web Api中的Post Stream

你好可爱的Stack Overflow人.从昨天起我就遇到了问题,从那时起我一直在浏览.我有一个UWP客户端和ASP.NET核心Web Api.我只想向我的网络api发送一个流,但事实上这比我想象的更难.

我有一个课,我只有一个属性.Stream您可以在下面看到该属性:

public class UploadData
{
    public Stream InputData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

那么这是我的Web Api中的代码:

// POST api/values
[HttpPost]
public string Post(UploadData data)
{
    return "test";
}
Run Code Online (Sandbox Code Playgroud)

我试图从体内读取流但结果是一样的.我可以点击post方法UploadData不是null但我InputData总是null.

这是我的UWP的邮寄请求代码.

private async void PostStreamButton_OnClick(object sender, RoutedEventArgs e)
{
    using (var client = new HttpClient())
    {
        var dummyBuffer = new UnicodeEncoding().GetBytes("this is dummy stream");
        var dummyStream = new MemoryStream(dummyBuffer).AsRandomAccessStream().AsStream();

        var requestContent = new MultipartFormDataContent();
        var inputData = new StreamContent(dummyStream);
        inputData.Headers.ContentType = …
Run Code Online (Sandbox Code Playgroud)

c# .net-core uwp asp.net-core asp.net-core-webapi

17
推荐指数
1
解决办法
9350
查看次数

ASP.net核心web api:使用Facebook/Google OAuth访问令牌进行身份验证

几天来,我正试图通过Google和Facebook获得OAuth身份验证,以便在我的ASP.net核心web api项目中工作.

我现在的状态是:

  • 我有一个ASP.net核心Web Api项目,用户需要在其中进行身份验证
  • 我有一个有角度的2 web应用程序,它应该使用我的web api(带身份验证)
  • 我有一个Android应用程序,它应该使用我的web api(带身份验证)

我的目标是:

  • 使用Google/Facebook作为OAuth提供商进行登录
  • 稍后:添加自己的用户帐户(可能使用IdentityServer4)
  • 无需重定向到特殊的登录网站(如IdentityServer4解决方案).只需点击应用中的facebook/google按钮,即可访问,完成!

在我的Android和角度应用程序中,我能够从谷歌/ Facebook检索访问令牌.现在,我想使用OAuth隐式流,使用给定的访问令牌对我的web api上的用户进行身份验证(将令牌作为承载令牌放入标头中)

有我的问题:有没有任何genric方式来轻松做到这一点?我不想使用facebook/google SDK.

我试过以下:

  • 使用IdentityServer4:有了这个,我可以在我的webapi上使用facebook/google登录,但是需要重定向到IdentityServer4登录页面.有没有办法在我的应用程序中点击google/fb-Button并登录,而无需重定向到identityServer登录页面?
  • 使用谷歌/ Facebook验证的中间件(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/):但是他们没有验证我发送承载令牌(试过无数种方法来实现适当的验证).这甚至可以在web api中使用吗?
  • 试图使用Microsoft.AspNetCore.Authentication.JwtBearer-Middleware并自己为google/facebook添加必要的选项,但也没有验证(以及无数次尝试)

在过去的几天里,我已经尝试了很多可能的解决方案,我完全陷入困境并且忘记了为实现这一目标我需要做些什么.在这一点上,我已经阅读了几乎每个asp.net web api oauth教程/ stackoverflow条目,但无法弄清楚如何在我的情况下使用这个我想要的.大多数教程仅适用于mvc-Websites或使用IdentityServer4重定向到其登录页面.

任何建议或解决方案?我错过了什么?

c# authentication google-oauth asp.net-core-webapi angular

17
推荐指数
1
解决办法
5359
查看次数

.NET Core 2.2退出目标进程而未引发CoreCLR启动事件错误

我想调试基于.NET Core 2.2的空WebApi项目。

我安装Core 2.2 SDK x86了目标框架并将其更改为2.2:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

当我开始调试该项目时,IIS开始运行,但是在路由中api/values我什么也没看到(它永远加载),并且出现此错误:

在没有引发CoreCLR启动事件的情况下退出了目标进程。确保将目标进程配置为使用.NET Core。如果目标进程未在.NET Core上运行,则可能会出现这种情况

在我的解决方案WPFClass Library项目中。我想做到WebApi这一点。就像我说的那样,它的空基项目由发起Visual Studio 2019。我刚刚安装了Core 2.2为什么会收到该错误以及我做错了什么?

在此处输入图片说明

c# asp.net-core asp.net-core-webapi visual-studio-2019 .net-core-2.2

17
推荐指数
8
解决办法
1万
查看次数