Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 上载文档后的重定向操作无效_C#_Asp.net Mvc_Asp.net Core_Post Redirect Get - Fatal编程技术网

C# 上载文档后的重定向操作无效

C# 上载文档后的重定向操作无效,c#,asp.net-mvc,asp.net-core,post-redirect-get,C#,Asp.net Mvc,Asp.net Core,Post Redirect Get,我定义了一个简单的视图,请求用户选择要上传的文件。 该文件存储在模型(视图的模型)中,然后在POST方法中处理。 上传文件后,我将新模型(文件的结果)保存到TempData中,以便将其传递到下一个要显示的视图,然后由用户验证内容 一切都很好,直到重定向到没有做任何事情,我不知道我在这里做错了什么 下面是我所做工作的一个例子: [HttpGet] public IActionResult Index() { return View();

我定义了一个简单的视图,请求用户选择要上传的文件。 该文件存储在模型(视图的模型)中,然后在POST方法中处理。 上传文件后,我将新模型(文件的结果)保存到TempData中,以便将其传递到下一个要显示的视图,然后由用户验证内容

一切都很好,直到重定向到没有做任何事情,我不知道我在这里做错了什么

下面是我所做工作的一个例子:

[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);
        }
[HttpGet]
公共IActionResult索引()
{
返回视图();
}
[HttpPost]
公共IActionResult索引(ImportIndexViewModel模型)
{
如果(!ModelState.IsValid)
返回视图(模型);
if(model.File==null)
{
AddModelError(“文件”,“文件为空”);
返回视图(模型);
}
var extension=Path.GetExtension(model.FileName);
如果(扩展名!=“.xlsx”)
{
AddModelError(“文件扩展名”,“文件类型未经授权。请使用正确的模板文件”);
返回视图(模型);
}
var uploads=Path.Combine(_webHostEnvironment.WebRootPath,“uploads”);

如果(model.File.Length我解决了它:它来自TempData。 在我使用的.NetCore 3.0中,TempData需要使用cookie或会话。 我启用了会话,然后重定向再次工作,没有对我的代码做任何更改!
希望这会对其他人有所帮助。

您是否尝试使用
Put
而不是
Post
使用
return RedirectToAction(name of(ImportController.Upload)、typeof(ImportController.GetControllerName());
何时
返回RedirectToAction(“Upload”)
产生相同的结果,而且更简单?我使用这些nameof和GetControllerName方法来确保如果我在某个地方更改了名称,我会看到使用它的任何地方。我也在cshtml和Url链接中使用此技巧。我多年来就习惯使用它,当然,如果在某个地方使用它,重命名或搜索时这会更好e而不是字符串值;)PUT给出相同的结果不幸的是您确定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
    }