上传文档后的 RedirectToAction 不起作用
RedirectToAction after uploading a document is not working
我定义了一个简单的视图,要求用户选择要上传的文件。
该文件存储在模型(视图的模型)中,然后在 POST 方法中进行处理。
文件上传后,我将新模型(文件的结果)保存到 TempData 中,以便将其传递给下一个要显示的视图,稍后由用户验证内容。
一切正常,直到 redirecttoaction 什么也没做,我不知道我在这里做错了什么
这是我所做的一个例子:
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(ImportIndexViewModel model)
{
if (!ModelState.IsValid)
return View(model);
if (model.File == null)
{
ModelState.AddModelError("File", "File is null");
return View(model);
}
var extension = Path.GetExtension(model.FileName);
if (extension != ".xlsx")
{
ModelState.AddModelError("File extension", "File type is not authorized. Please use the correct template file");
return View(model);
}
var uploads = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
if (model.File.Length <= 0)
{
ModelState.AddModelError("File size", "File length is <= 0");
return View(model);
}
var resultModel = InterclubsApiClient.GetInterclubsReaderModel(model.File, uploads).GetAwaiter().GetResult();
TempData.Put<InterclubsReaderModel>("InterclubsReaderModel", resultModel);
return RedirectToAction(nameof(ImportController.Upload), typeof(ImportController).GetControllerName());
}
[HttpGet]
public IActionResult Upload()
{
var model = TempData.Get<InterclubsReaderModel>("InterclubsReaderModel");
if (model == null)
return BadRequest(ErrorHelper.GetModelStateDictionary("InterclubsReaderModel", "Model is null when retrieved from TempData"));
return View(model);
}
正在上传,因为我可以在上传文件夹中找到该文件。该模型也是正确的,因为我可以在其中找到值,但为什么重定向不起作用?
相反,该页面停留在那里,我无法对其进行任何操作。如果我使用 Chrome,它会说该网站无法访问(就像 IIS 缺少 link)。
感谢您的帮助。
编辑:回答问题:您确定这是 nameof(...) 给出的正确方法名称吗
这里是:
第二次编辑:
你们觉得这里有什么不对吗?
public class Startup
{
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; }
#region Constructor
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
Environment = env;
}
#endregion
#region Configure services
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication("InterclubsCookieAuth")
.AddCookie("InterclubsCookieAuth", config =>
{
config.Cookie.Name = "Interclubs.Cookie";
config.LoginPath = "/Connect/Login";
config.LogoutPath = "/Connect/Logout";
config.ExpireTimeSpan = TimeSpan.FromHours(15);
});
services.AddAuthorization(config =>
{
var defaultAuthBuilder = new AuthorizationPolicyBuilder("InterclubsCookieAuth");
var defaultAuthPolicy = defaultAuthBuilder
.RequireAuthenticatedUser()
.Build();
config.DefaultPolicy = defaultAuthPolicy;
});
services.AddHttpContextAccessor();
services.AddMemoryCache();
services.AddSession();
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Enables .Net Core to refresh updated views in browser while debugging
var builder = services.AddControllersWithViews();
builder.AddRazorRuntimeCompilation(options =>
{
var libraryPath = Path.GetFullPath(Path.Combine(Environment.ContentRootPath));
options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
});
}
#endregion
#region Configuration
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler($"/{typeof(HomeController).GetControllerName()}/{nameof(HomeController.Error)}");
app.UseHsts(options => options.MaxAge(days: 365).IncludeSubdomains());
}
app.UseXContentTypeOptions();
app.UseXfo(options => options.SameOrigin());
app.UseXXssProtection(options => options.EnabledWithBlockMode());
app.UseReferrerPolicy(options => options.NoReferrer());
app.UseHttpsRedirection();
var contentTypeProvider = new FileExtensionContentTypeProvider();
if (!contentTypeProvider.Mappings.ContainsKey(".svg"))
{
contentTypeProvider.Mappings.Add(".svg", "image/svg+xml");
}
if (!contentTypeProvider.Mappings.ContainsKey(".woff"))
{
contentTypeProvider.Mappings.Add(".woff", "application/font-woff");
}
if (!contentTypeProvider.Mappings.ContainsKey(".woff2"))
{
contentTypeProvider.Mappings.Add(".woff2", "application/font-woff2");
}
var staticFilesOptions = new StaticFileOptions
{
ContentTypeProvider = contentTypeProvider
};
app.UseStaticFiles(staticFilesOptions);
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: $"{{controller={typeof(ConnectController).GetControllerName()}}}/{{action={nameof(ConnectController.Login)}}}");
});
}
#endregion
}
我解决了:它来自 TempData。
在我使用的.NetCore 3.0 中,TempData 需要使用Cookies 或Session。
我启用了会话,然后重定向又开始工作了,而没有对我的代码进行任何更改!
希望这会对其他人有所帮助。
我定义了一个简单的视图,要求用户选择要上传的文件。 该文件存储在模型(视图的模型)中,然后在 POST 方法中进行处理。 文件上传后,我将新模型(文件的结果)保存到 TempData 中,以便将其传递给下一个要显示的视图,稍后由用户验证内容。
一切正常,直到 redirecttoaction 什么也没做,我不知道我在这里做错了什么
这是我所做的一个例子:
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(ImportIndexViewModel model)
{
if (!ModelState.IsValid)
return View(model);
if (model.File == null)
{
ModelState.AddModelError("File", "File is null");
return View(model);
}
var extension = Path.GetExtension(model.FileName);
if (extension != ".xlsx")
{
ModelState.AddModelError("File extension", "File type is not authorized. Please use the correct template file");
return View(model);
}
var uploads = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
if (model.File.Length <= 0)
{
ModelState.AddModelError("File size", "File length is <= 0");
return View(model);
}
var resultModel = InterclubsApiClient.GetInterclubsReaderModel(model.File, uploads).GetAwaiter().GetResult();
TempData.Put<InterclubsReaderModel>("InterclubsReaderModel", resultModel);
return RedirectToAction(nameof(ImportController.Upload), typeof(ImportController).GetControllerName());
}
[HttpGet]
public IActionResult Upload()
{
var model = TempData.Get<InterclubsReaderModel>("InterclubsReaderModel");
if (model == null)
return BadRequest(ErrorHelper.GetModelStateDictionary("InterclubsReaderModel", "Model is null when retrieved from TempData"));
return View(model);
}
正在上传,因为我可以在上传文件夹中找到该文件。该模型也是正确的,因为我可以在其中找到值,但为什么重定向不起作用?
相反,该页面停留在那里,我无法对其进行任何操作。如果我使用 Chrome,它会说该网站无法访问(就像 IIS 缺少 link)。
感谢您的帮助。
编辑:回答问题:您确定这是 nameof(...) 给出的正确方法名称吗
这里是:
第二次编辑: 你们觉得这里有什么不对吗?
public class Startup
{
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; }
#region Constructor
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
Environment = env;
}
#endregion
#region Configure services
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication("InterclubsCookieAuth")
.AddCookie("InterclubsCookieAuth", config =>
{
config.Cookie.Name = "Interclubs.Cookie";
config.LoginPath = "/Connect/Login";
config.LogoutPath = "/Connect/Logout";
config.ExpireTimeSpan = TimeSpan.FromHours(15);
});
services.AddAuthorization(config =>
{
var defaultAuthBuilder = new AuthorizationPolicyBuilder("InterclubsCookieAuth");
var defaultAuthPolicy = defaultAuthBuilder
.RequireAuthenticatedUser()
.Build();
config.DefaultPolicy = defaultAuthPolicy;
});
services.AddHttpContextAccessor();
services.AddMemoryCache();
services.AddSession();
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Enables .Net Core to refresh updated views in browser while debugging
var builder = services.AddControllersWithViews();
builder.AddRazorRuntimeCompilation(options =>
{
var libraryPath = Path.GetFullPath(Path.Combine(Environment.ContentRootPath));
options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
});
}
#endregion
#region Configuration
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler($"/{typeof(HomeController).GetControllerName()}/{nameof(HomeController.Error)}");
app.UseHsts(options => options.MaxAge(days: 365).IncludeSubdomains());
}
app.UseXContentTypeOptions();
app.UseXfo(options => options.SameOrigin());
app.UseXXssProtection(options => options.EnabledWithBlockMode());
app.UseReferrerPolicy(options => options.NoReferrer());
app.UseHttpsRedirection();
var contentTypeProvider = new FileExtensionContentTypeProvider();
if (!contentTypeProvider.Mappings.ContainsKey(".svg"))
{
contentTypeProvider.Mappings.Add(".svg", "image/svg+xml");
}
if (!contentTypeProvider.Mappings.ContainsKey(".woff"))
{
contentTypeProvider.Mappings.Add(".woff", "application/font-woff");
}
if (!contentTypeProvider.Mappings.ContainsKey(".woff2"))
{
contentTypeProvider.Mappings.Add(".woff2", "application/font-woff2");
}
var staticFilesOptions = new StaticFileOptions
{
ContentTypeProvider = contentTypeProvider
};
app.UseStaticFiles(staticFilesOptions);
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: $"{{controller={typeof(ConnectController).GetControllerName()}}}/{{action={nameof(ConnectController.Login)}}}");
});
}
#endregion
}
我解决了:它来自 TempData。 在我使用的.NetCore 3.0 中,TempData 需要使用Cookies 或Session。 我启用了会话,然后重定向又开始工作了,而没有对我的代码进行任何更改! 希望这会对其他人有所帮助。