代码之家  ›  专栏  ›  技术社区  ›  Kurkula

使用Asp.Net核心路由,然后重定向到反应路由

  •  0
  • Kurkula  · 技术社区  · 7 年前

    现在,我的应用程序根据路由通过控制器和操作,并在控制器操作定义的视图处停止。我正在试图了解如何重定向用户使用反应路线现在。我尝试使用return redirecttoaction和returnredirecttoroute,但没有成功。

    我的Asp.Net核心MVC操作

    [Authorize]
    public ActionResult Index()
    {
        var IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
        var UserName = "Guest";
        if (IsAuthenticated)
        {
            UserName = HttpContext.User.Identity.Name;
        }
        TempData["userName"] = UserName;
    
        //return View();
        return Redirect("my react first page");
    }
    

    我尝试返回重定向(“我的第一页”);

    用于路由的“我的启动文件”方法

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                {
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        app.UseExceptionHandler("/Error");
                        app.UseHsts();
                    }
    
                    app.UseHttpsRedirection();
                    app.UseStaticFiles();
                    app.UseSpaStaticFiles();
                    app.UseAuthentication();
    
    
    //MVC Part. I am trying this to authorize as FIRST step
                    app.UseMvc(routes =>
                    {
                        routes.MapRoute(
                            name: "default",
                            template: "{controller=DataAccess}/{action=Index}/{id?}");
                    });
    
    // React part I am trying this to be called once Authentication is done in controller action. Trying to call this as a SECOND step
    
                    app.UseSpa(spa =>
                    {
                        spa.Options.SourcePath = "ClientApp";
    
                        if (env.IsDevelopment())
                        {
                            spa.UseReactDevelopmentServer(npmScript: "start");
                        }
                    });
                }
    

    如果我执行重定向并强制执行反应路线,是否会出现缺少反应路线功能的任何问题?我看到了 用户eactdevelopmentserver(npmScript:“开始”); 如果我重定向,则显示超时会花费更多时间。是否有任何解决方案可以将用户重定向到控制器操作执行所有授权并使用默认路由机制?

    是否有任何选项可以先运行react server并执行路由,因为启动服务器会花费更多时间导致超时。

    0 回复  |  直到 7 年前
        1
  •  4
  •   JohnnBlade    7 年前

    不要为两者设置相同的路由,让服务器找到非React视图,让React拥有自己的路由和视图/模板

        2
  •  1
  •   Manoj Choudhari    7 年前

    请注意,客户端路由仅限于浏览器。服务器不知道它们。

    当您尝试在react中更改页面时,浏览器(不向服务器发送请求)会将用户重定向到其他页面-前提是您不需要服务器提供任何其他信息来进行此重定向。

    在我看来,您应该以这样的方式设计应用程序:您的服务器不应该直接影响客户端路由中定义的路由。

    基于asp.net服务器上的某些决策进行路由的理想流程(在我看来也是如此)是:

    • 若要重定向用户,则应将其重定向到何处。

    此逻辑(或任何其他类似逻辑)还将使服务器端逻辑与客户端技术完全解耦。

        3
  •  1
  •   grizzthedj dusa bhargava    7 年前

    在React中,当用户登录时,调用控制器操作来执行身份验证/授权。然后,您可以根据响应使用React进行适当重定向(例如,成功登录会重定向到用户的仪表板,失败登录会显示身份验证错误等)

        4
  •  1
  •   Moh. Anwer    7 年前

    我已经用.NETCore解决了这个问题,并对其进行了响应。

    为路由设置一个HOC。让该hoc点击后端,查看用户是否获得授权。如果没有,则重定向到登录。

    .Net核心: 设置HOC的基本路径,以命中并验证用户是否已授权。

    下面是对我的github的完整描述(尽管它使用jwt令牌): https://github.com/moh704/AuthenticationExample

    //Routing with HOC:
    class App extends Component {
      render() {
        return (
            <Provider store={store}>
              <ConnectedRouter history={history}>
                <Switch>
                  <Route component={SignIn} exact path='/'/>
                  <PrivateRoute component={Home} path='/Home'/> //Token will have to be valid in order to access this route.
                </Switch>
              </ConnectedRouter>
            </Provider>
        );
      }
    }
    
    //PrivateRoute Component:
    interface PrivateRouteProps extends RouteProps {
      component:
        | React.ComponentType<RouteComponentProps<any>>
        | React.ComponentType<any>;
    }
    
    interface State {
      validatingUser: boolean,
      userAllowed: boolean
    }
    
    class PrivateRouter extends React.Component<PrivateRouteProps, State> {
      state: State = {
        validatingUser: true,
        userAllowed: false
      };
    
      componentDidMount(): void {
        this.checkUserStatus();
      }
    
      checkUserStatus = async() => {
        const token = localStorage.getItem('token');
        if (token){
          await axios.get(UserRoutes.GET_TOKEN_STATUS)
            .then(() => this.setState({userAllowed: true, validatingUser: false}))
            .catch(() => this.setState({userAllowed: true, validatingUser: false}));
        } else
          this.setState({userAllowed: false, validatingUser: false});
      };
    
      render() {
        const { component, ...rest} = this.props;
        return(
          !this.state.validatingUser ?
            <Route
              {...rest}
              render={props =>
                this.state.userAllowed ? (
                  <this.props.component {...props} />
                ) : (
                  <Redirect // <---- **Redirect magic happens here you're aiming for**
                    to={{
                      pathname: "/"
                    }}
                  />
                )
              }
            /> : <div>loading...</div>
        )
      }
    }
    export default PrivateRouter;
    

    对于.net,只需创建一个简单的get路由,如果获得授权,它将返回OK。否则,将返回未经授权或禁止的:

    [HttpGet]
    [Authorize]
    public IActionResult CheckUserState()
    {
       return Ok();
    }
    
        5
  •  0
  •   user833831    7 年前

    您可以使主页成为它返回的视图。

    然后,您的控制器可以返回该视图,或者您可以创建一个控制器,该控制器将返回该视图并重定向到该视图。