В этом посте Спросили, как получить текущий UserId с контроллером odata.
Есть 2 метода. В этих методах использовался AbpSession. Один из них:
public long? GetCurrentUserId()
{
return _userManager.AbpSession.UserId;
}
Используя этот фрагмент, я не смог получить идентификатор пользователя. Это всегда было нулевым. Перед вызовом метода GetCurrentUserId я выполнил вход с помощью приложения Web.Mvc. Но UserId всегда нулевой. Мой контроллер:
//[AbpMvcAuthorize]
public class UsersController : AbpODataEntityController<User,long>, ITransientDependency
{
private readonly UserManager _userManager;
public UsersController(IRepository<User, long> repository, UserManager userManager) : base(repository)
{
_userManager = userManager;
}
public long? GetCurrentUserId()
{
//var test= _userManager.GetUserAsync(User).Result.EmailAddress;
var bak= _userManager.AbpSession.UserId;
return _userManager.AbpSession.UserId;
}
public int? GetCurrentTenantId()
{
return _userManager.AbpSession.TenantId;
}
}
и запуск в проекте Web.Host:
builder.EntityType<User>().Collection
.Function("GetCurrentUserId")
.Returns<long>();
Я должен также сказать, что, если я использую атрибут [[AbpMvcAuthorize] »в моем контроллере оддаты, мой результат оддаты будет
{"result": null, "targetUrl": null, "success": false, "error": {"code": 0, "message": "Текущий пользователь не вошел в приложение!", " подробности ": нулевая" validationErrors ": нулевая}," unAuthorizedRequest ": правда," __ ABP ": правда}
даже если я вошел в приложение Web.Mvc. Это говорит
Текущий пользователь не вошел в приложение!
Должен ли я как-нибудь войти в хост-приложение?
Из-за некоторых причин безопасности файл My appSettings в приложении Web.Mvc не должен содержать строки подключения к базе данных. Каждый пользователь должен войти в систему с помощью удаленных служб. Моя главная проблема в том, что я не знаю, как войти в систему с помощью оддаты или классических методов webapi.
Это класс StartUp, расположенный в приложении Web.Host
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Castle.Facilities.Logging;
using Swashbuckle.AspNetCore.Swagger;
using Abp.AspNetCore;
using Abp.AspNetCore.OData.Configuration;
using Abp.Castle.Logging.Log4Net;
using Abp.Extensions;
using TSE.DergiAbone.Configuration;
using TSE.DergiAbone.Identity;
using Abp.AspNetCore.SignalR.Hubs;
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNet.OData.Formatter;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using TSE.DergiAbone.Authorization.Users;
using TSE.DergiAbone.Cities;
using TSE.DergiAbone.Countries;
using TSE.DergiAbone.Districts;
using TSE.DergiAbone.Neighborhoods;
using TSE.DergiAbone.Towns;
namespace TSE.DergiAbone.Web.Host.Startup
{
public class Startup
{
private const string _defaultCorsPolicyName = "localhost";
private readonly IConfigurationRoot _appConfiguration;
public Startup(IHostingEnvironment env)
{
_appConfiguration = env.GetAppConfiguration();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// MVC
//services.AddMvc(
// options => options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName))
//);
services.AddMvc(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName));
options.Filters.Add<ResultFilter>();
}).AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
IdentityRegistrar.Register(services);
AuthConfigurer.Configure(services, _appConfiguration);
services.AddSignalR();
// Configure CORS for angular2 UI
services.AddCors(
options => options.AddPolicy(
_defaultCorsPolicyName,
builder => builder
.WithOrigins(
// App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
_appConfiguration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
)
);
// Swagger - Enable this line and the related lines in Configure method to enable swagger UI
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "DergiAbone API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);
// Define the BearerAuth scheme that's in use
options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
});
services.AddOData();
// Workaround: https://github.com/OData/WebApi/issues/1177
services.AddMvcCore(options =>
{
foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
});
// Configure Abp and Dependency Injection
return services.AddAbp<DergiAboneWebHostModule>(
// Configure Log4Net logging
options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
)
);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework.
app.UseCors(_defaultCorsPolicyName); // Enable CORS!
app.UseStaticFiles();
app.UseAuthentication();
app.UseAbpRequestLocalization();
app.UseSignalR(routes =>
{
routes.MapHub<AbpCommonHub>("/signalr");
});
app.UseOData(builder =>
{
builder.EntitySet<Abone.Abone>("Abones").EntityType.Expand().Count().Filter().OrderBy().Page();
builder.EntitySet<Abonelik.Abonelik>("Aboneliks").EntityType.Count().Expand().Filter().OrderBy().Page();
builder.EntitySet<Test.Test>("Tests").EntityType.Count().Expand().Filter().OrderBy().Page();
builder.EntitySet<Country>("Countries").EntityType.Count().Expand().Filter().OrderBy().Page();
builder.EntitySet<City>("Cities").EntityType.Count().Expand().Filter().OrderBy().Page();
builder.EntitySet<Town>("Towns").EntityType.Count().Expand().Filter().OrderBy().Page().Select();
builder.EntitySet<District>("Districts").EntityType.Count().Expand().Filter().OrderBy().Page();
builder.EntitySet<Neighborhood>("Neighborhoods").EntityType.Count().Expand().Filter().OrderBy().Page();
builder.EntitySet<SinifDergi.SinifDergi>("DergiSinifs").EntityType.Count().Expand().Filter().OrderBy().Page().Select();
builder.EntitySet<User>("Users").EntityType.Count().Expand().Filter().OrderBy().Page().Select();
//Action ekleme
//ODataModelBuilder builderr = new ODataConventionModelBuilder();
//builderr.EntitySet<Test.Test>("Products");
//builderr.Namespace = "ProductService";
//builderr.EntityType<Test.Test>()
// .Action("Rate")
// .Parameter<int>("Rating");
//builder.EntitySet<Town>("Towns").EntityType.Action("Test").Parameter<string>("TestValue");
//builder.EntitySet<Town>("Towns").EntityType.Action("Test");
builder.EntityType<Town>().Collection
.Function("Test")
.Returns<string>();
//.Parameter<string>("param");
builder.EntityType<Town>().Collection//.Action("stringTest")
.Function("stringTest")
.Returns<IActionResult>()
.Parameter<string>("param");
builder.EntityType<Town>().Collection//.Action("stringTest")
.Function("GetTownsByCityId")
.Returns<IActionResult>()
.Parameter<int>("cityID");
builder.EntityType<User>().Collection //.Action("stringTest")
.Function("GetCurrentUserId")
.Returns<long>();
//.Parameter<int>("cityID");
builder.EntityType<Abone.Abone>().Collection//.Action("stringTest")
.Function("TCKimlikNoBelirliDergiAboneligiIcinDahaOnceKullanilmisMi")
.Returns<bool>()
.Parameter<string>("TCKimlikNo");
});
// Return IQueryable from controllers
app.UseUnitOfWork(options =>
{
options.Filter = httpContext =>
{
return httpContext.Request.Path.Value.StartsWith("/odata");
};
});
app.UseMvc(routes =>
{
routes.MapODataServiceRoute(app);
routes.MapRoute(
name: "defaultWithArea",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(_appConfiguration["App:ServerRootAddress"].EnsureEndsWith('/') + "swagger/v1/swagger.json", "DergiAbone API V1");
options.IndexStream = () => Assembly.GetExecutingAssembly()
.GetManifestResourceStream("TSE.DergiAbone.Web.Host.wwwroot.swagger.ui.index.html");
}); // URL: /swagger
}
}
}
Не могли бы вы рассказать мне о правильном способе входа пользователя с помощью удаленных служб? Спасибо.
Я вызываю метод GetCurrentUserId () в проекте Web.Core в пользовательском контроллере, который называется UsersController. И содержимое этого контроллера:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.AspNetCore.OData.Controllers;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TSE.DergiAbone.Authorization.Users;
using TSE.DergiAbone.Countries;
using TSE.DergiAbone.Towns;
namespace TSE.DergiAbone.Web.Host.Controllers
{
//[EnableQueryWithSearch]
[AbpMvcAuthorize]
public class UsersController : AbpODataEntityController<User,long>, ITransientDependency
{
private readonly UserManager _userManager;
public UsersController(IRepository<User, long> repository, UserManager userManager) : base(repository)
{
_userManager = userManager;
}
public long? GetCurrentUserId()
{
//var test= _userManager.GetUserAsync(User).Result.EmailAddress;
var bak= _userManager.AbpSession.UserId;
return _userManager.AbpSession.UserId;
}
public int? GetCurrentTenantId()
{
return _userManager.AbpSession.TenantId;
}
}
}