Asp.Net Core Mvc3.1重定向不起作用

一、问题描述

前端妹纸使用Ajax调用后台接口,我这边在后台会判断用户是否登录,如果没有登录,重定向到登录页。

后台代码:

    public class ActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
                context.Result = new RedirectResult("~/Login/Index");
                //context.HttpContext.Response.Redirect("~/Login/Index");
        }
    }

而这段代码不起作用。

二、解决

为了证明自己的清白,所以自己写了一段测试代码去测试是否可以重定向。

@using (Html.BeginRouteForm("Areas", new { Area = "Module", Controller = "User", Action = "GetList" }, FormMethod.Get))
{
    <div><input type="submit"  value="跳转" /></div>}
}

结果证明自己是清白的,可以跳转到登录页。那么为什么前端妹纸使用ajax不能跳转呢?那写一段ajax调用测试一下

function aa() {
        debugger 
        $.ajax({
            url: "/Module/User/GetList",
            data: "",
            type: "GET",
            dataType: "json",
            async: false,
            cache: false,
            success: function (res) {

            },
            error: function (e) {

            }
        });

结果是不能跳转到登录页

三、调用原因

查看前辈写的代码,他这样写

if (context.HttpContext.Request.IsAjaxRequest())
                            {
                                TData obj = new TData();
                                obj.Message = "抱歉,没有权限";
                                context.Result = new JsonResult(obj);
                            }
                            else
                            {
                                context.Result = new RedirectResult("~/Home/NoPermission");
                            }

那结论就是Ajax发起请求时,重定向的工作需要前端来做;非Ajax请求时,重定向的工作后端来做。

四、遗留问题

具体Ajax请求时后端不能重定向的原因实在找不到了,这个问题先记录吧

posted @ 2020-12-22 16:09  刘泽岐  阅读(865)  评论(0)    收藏  举报