我试图在asp.net核心中使用TempData但是我在TempData的get方法上得到一个空值。任何人都可以告诉我如何在asp.net核心中使用TempData
以下是我根据研究添加的内容。
Project.json文件
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Routing": "1.0.1",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.1.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
"Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",
"Microsoft.EntityFrameworkCore.Design": "1.1.0",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0",
"DataBase": "1.0.0-*",
"UnitOfWork": "1.0.0-*",
"ViewModel": "1.0.0-*",
"Common": "1.0.0-*",
"System.IdentityModel.Tokens.Jwt": "5.0.0",
"Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.AspNetCore.Session": "1.1.0",
"Microsoft.Extensions.Caching.Memory": "1.1.0"
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
start.cs文件
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddSession();
// Add framework services.
services.AddMvc();
services.AddTransient<IMarketUOW, MarketUow>();
services.AddTransient<ICategoryUow, CategoryUow>();
services.AddTransient<IUserProfileUow, UserProfileUow>();
services.AddTransient<IItemUow, ItemUow>();
services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>));
var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<EmakitiContext>(options => options.UseSqlServer(connection));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
这是tempdata的实现。当调用此方法时,我可以看到TempData中的值。
[HttpGet("{pageNumber}")]
public GenericResponseObject<List<MarketViewModel>> GetMarketList(int pageNumber)
{
TempData["Currentpage"] = pageNumber;
TempData.Keep("Currentpage");
GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>();
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed;
try
{
var marketItem = _iMarketUow.GetMarketList(pageNumber);
genericResponseObject.Data = marketItem.Item1;
var totalPages = (int)Math.Ceiling((decimal)marketItem.Item2 / (decimal)10);
genericResponseObject.TotalPage = totalPages;
genericResponseObject.IsSuccess = true;
genericResponseObject.Message = ConstaintStingValue.Tag_SuccessMessageRecord;
genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionSuccess;
}
catch (Exception exception)
{
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = exception.Message;
genericResponseObject.ErrorCode = exception.HResult;
genericResponseObject.ExceptionErrorMessage = exception.StackTrace;
}
return genericResponseObject;
}
但是下面的方法在临时数据中有空值。
[HttpPost]
public GenericResponseObject<List<MarketViewModel>> AddUpdateMarket([FromBody] MarketViewModel marketViewModel)
{
GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>();
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed;
if (marketViewModel!= null && ModelState.IsValid)
{
try
{
_iMarketUow.AddUpdateMarketList(marketViewModel);
genericResponseObject = GetMarketList(Convert.ToInt16(TempData.Peek("Currentpage")));
}
catch (Exception exception)
{
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = exception.Message;
genericResponseObject.ErrorCode = exception.HResult;
genericResponseObject.ExceptionErrorMessage = exception.StackTrace;
}
}
else
{
genericResponseObject.Message = ConstaintStingValue.Tag_InputDataFormatNotMatch;
}
return genericResponseObject;
}
以下是调试会话的图像
答案 0 :(得分:53)
迁移到ASP Core 2.1之后,出现了此问题,并在工作了一天后找到了解决方案:
在Startup.Configure()中
In [312]: df1['label'] = df1.merge(df2[['c1', 'c2']], how='left', indicator=True
)['_merge'].eq('both').astype(int)
In [313]: df1
Out[313]:
c1 c2 label
0 dr123 di878 0
1 dr987 di082 1
2 dr751 di715 1
3 dr156 di083 0
应该在In [88]: cols = ['c1', 'c2']
In [89]: mapper = {tuple(x[cols]) for _, x in df2.iterrows()}
In [90]: df1.apply(lambda x: tuple(x[['c1', 'c2']]) in mapper, axis=1).astype(int)
Out[90]:
0 0
1 1
2 1
3 0
dtype: int32
之后
答案 1 :(得分:15)
请将您的所有软件包升级到相同版本的1.1.0
添加缓存服务。以下是在TempData
Asp.Net Core
所需的内容
<强> Project.json 强>
"Microsoft.AspNetCore.Session": "1.1.0"
这是Startup.cs文件。 - ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddSession();
services.AddMvc();
}
和配置方法。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
现在尝试使用TempData
,它会起作用。
您可以使用设置ASPNETCORE_ENVIRONMENT =开发环境变量来设置环境。
PS
ASP.NET Core MVC
公开TempData
上的Controller
属性。 TempData
可用于存储瞬态数据,该瞬态数据仅需要在当前请求之后针对单个请求可用。
当读取TempDataDictionary
中的对象时,将在该请求结束时将其标记为删除。
Peek
和Keep
方法允许您读取值而不将其标记为删除。假设我们回到第一个将值保存到TempData
的请求。
使用Peek
,您只需一次调用就可以获得值,而不会将其标记为删除。
//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
使用Keep
指定要保留的标记为删除的密钥。检索对象以及稍后将其保存为删除是2个不同的调用。
//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
答案 2 :(得分:5)
official docs中所述的中间件顺序没有问题,即:
但是,当我们使用Cookie策略实施(UseCookiePolicy)时,仅将要发送到浏览器的必需 cookie和来自Tempdata提供程序的Cookie都不是必需的,因此出现了问题。因此,我们必须根据official documentation将其设置为必不可少:
Tempdata提供程序cookie不是必需的。如果禁用了跟踪,则Tempdata提供程序将无法运行。要在禁用跟踪时启用Tempdata提供程序,请在Startup.ConfigureServices
中将TempData cookie标记为必不可少的。
// The Tempdata provider cookie is not essential. Make it essential
// so Tempdata is functional when tracking is disabled.
services.Configure<CookieTempDataProviderOptions>(options => {
options.Cookie.IsEssential = true;
});
添加这些行应该可以解决您的问题,而无需重新排序中间件。