在这个post中,有人询问如何使用odata控制器获取当前的UserId。有两种方法。在这些方法中使用了AbpSession。其中一个是:
public long? GetCurrentUserId()
{
return _userManager.AbpSession.UserId;
}
通过使用该片段,我无法获得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项目中的StartUp:
builder.EntityType<User>().Collection
.Function("GetCurrentUserId")
.Returns<long>();
我还应该说,如果我在odata控制器中使用'[AbpMvcAuthorize]'属性,我的odata结果是
{“result”:null,“targetUrl”:null,“success”:false,“error”:{“code”:0,“message”:“当前用户未登录到应用程序!”,“details”:空, “validationErrors”:空}, “unAuthorizedRequest”:真实的, “__ ABP”:真正}
即使我已登录Web.Mvc应用程序。它说
当前用户没有登录该应用程序!
我应该以某种方式登录主机应用程序吗?
由于某些安全原因,Web.Mvc应用程序中的My appSettings文件不应包含数据库连接字符串。每个用户都必须使用远程服务登录。我的主要问题是我不知道如何使用odata或经典的webapi方法登录用户。
这是位于Web.Host应用程序中的StartUp类
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
}
}
}
你能告诉我使用远程服务签署用户的正确方法吗?谢谢。
我在自定义控制器中调用UserController中的Web.Core项目中调用GetCurrentUserId()方法。并且该控制器的内容是:
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;
}
}
}
使用IAbpSession
public class UsersController : AbpODataEntityController<User,long>, ITransientDependency
{
private readonly IAbpSession _abpSession;
public UsersController(
IRepository<User, long> repository,
UserManager userManager,
IAbpSession abpSession
) : base(repository)
{
_userManager = userManager;
_abpSession = abpSession;
}
public long? GetCurrentUserId()
{
return _abpSession.GetUserId();
}
}