我试图在中间件中读取正文以进行身份验证,但是当请求到达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) 所以,我正在使用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
我正在遵循有关 .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) 从我的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
(编辑 - 找到正确的解决方案!见下文)
好的 - 这是我第一次尝试使用.Net Core 2.0和身份验证,虽然我过去曾使用过Web API 2.0,并且在过去几年中对各种MVC和Webforms ASP项目进行了相当广泛的工作.
我正在尝试使用.Net Core创建一个仅限Web API的项目.这将形成多租户应用程序的后端以生成一些报告,因此我需要能够对用户进行身份验证.通常的方法是使用JWT - 首先验证用户生成令牌,然后将其传递给客户端以在每个API请求上使用.将使用EF Core存储和检索数据.
我按照这篇文章找到了这个设置的基本方法,我设法让它工作正常 - 我有一个接受用户名/密码的控制器并返回一个令牌(如果有效),并且一些授权策略设置基于索赔.
我需要的下一件事是实际管理用户/密码/等.我以为我只是使用.Net核心身份,因为我会有很多现成的代码来担心用户/角色,密码等.我使用的是自定义User类和UserRole派生自标准IdentityUser和IdentityRole类的类,但我现在已经恢复到标准的那个.
我遇到的问题是我无法弄清楚如何添加身份并注册所有各种服务(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) 我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) 我有一个 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) 你好可爱的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) 几天来,我正试图通过Google和Facebook获得OAuth身份验证,以便在我的ASP.net核心web api项目中工作.
我现在的状态是:
我的目标是:
在我的Android和角度应用程序中,我能够从谷歌/ Facebook检索访问令牌.现在,我想使用OAuth隐式流,使用给定的访问令牌对我的web api上的用户进行身份验证(将令牌作为承载令牌放入标头中)
有我的问题:有没有任何genric方式来轻松做到这一点?我不想使用facebook/google SDK.
我试过以下:
在过去的几天里,我已经尝试了很多可能的解决方案,我完全陷入困境并且忘记了为实现这一目标我需要做些什么.在这一点上,我已经阅读了几乎每个asp.net web api oauth教程/ stackoverflow条目,但无法弄清楚如何在我的情况下使用这个我想要的.大多数教程仅适用于mvc-Websites或使用IdentityServer4重定向到其登录页面.
任何建议或解决方案?我错过了什么?
我想调试基于.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上运行,则可能会出现这种情况
在我的解决方案WPF和Class Library项目中。我想做到WebApi这一点。就像我说的那样,它的空基项目由发起Visual Studio 2019。我刚刚安装了Core 2.2为什么会收到该错误以及我做错了什么?
c# asp.net-core asp.net-core-webapi visual-studio-2019 .net-core-2.2
c# ×8
asp.net-core ×6
.net-core ×2
.net-6.0 ×1
angular ×1
google-oauth ×1
jwt ×1
oauth-2.0 ×1
swagger ×1
swagger-ui ×1
unauthorized ×1
uwp ×1