我是新来的,但对asp.net核心应用程序的开发没有反应。我正在尝试在Visual Studio中使用asp.net core + react模板创建一个react应用程序。我正在尝试先做一个Asp.Net MVC路由来调用具有[Authorize]属性的控制器操作,以确保对用户进行身份验证。我没有任何东西要显示在Asp.Net MVC视图中。我想立即重定向用户以响应通过asp.net mvc控制器操作对用户进行身份验证的默认路由。是否有任何特定的路由机制可以实现这一目标。
现在,我的应用程序根据路线通过控制器和动作,并停留在由控制器动作定义的视图上。我正在尝试了解如何立即重定向用户以使用反应路线。我尝试使用return redirecttoaction和returnredirecttoroute,但是没有运气。
我的Asp.Net Core 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");
}
我尝试了return Redirect(“我的反应首页”);
我用于路由的启动文件方法
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");
}
});
}
如果我进行重定向并强制使用React路由,会不会有任何问题缺少React Route功能?我看到这个 spa.UseReactDevelopmentServer(npmScript:“ start”); 需要更多的时间来显示超时(如果我执行重定向)。可以将用户重定向到控制器操作的任何解决方案都可以进行所有授权并使用默认路由机制吗?
是否可以选择先运行React Server并进行路由,因为启动服务器花费更多时间导致超时。
注意:我使用Create-React-App来创建我的应用。
答案 0 :(得分:3)
不要为两者设置相同的路由,让服务器找到非React视图,并让React拥有自己的路由和视图/模板
答案 1 :(得分:1)
您应该在react和ASP.NET Core中设置客户端路由。
请注意,客户端路由仅限于浏览器。服务器不知道它们。
当您尝试以响应方式更改页面时,浏览器(不向服务器发送请求)会将用户重定向到其他页面-前提是您不需要服务器的任何其他信息即可进行重定向。
我认为,您应该以一种不直接影响客户端路由中定义的路由的方式设计应用程序。
基于asp.net服务器上的某些决定进行路由的理想流程(再次,我认为)是:
此逻辑(或任何其他类似的逻辑)还将使服务器端逻辑与客户端技术完全脱钩。
答案 2 :(得分:1)
我不建议在服务器端进行任何形式的路由或重定向。这将使开发复杂化,并使工作量增加一倍。比较简单的方法是在客户端处理路由或重定向。从代码的角度来看,这也将更加易于维护。
在React中,当用户登录时,调用您的控制器操作以进行身份验证/授权。然后您可以根据响应使用React进行适当的重定向(例如,成功的登录将重定向到用户的仪表板,失败的登录将显示身份验证错误等)
答案 3 :(得分:1)
我已经使用.net core解决了这个问题,并且也做出了反应。
反应: 设置路由的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路由,如果获得授权,该路由将返回确定。否则,它将返回未经授权或被禁止的
[HttpGet]
[Authorize]
public IActionResult CheckUserState()
{
return Ok();
}
答案 4 :(得分:0)
您可以将主反应页面设为返回的视图。
然后您的控制器可以返回该视图,或者您可以使控制器返回该视图并重定向到该视图。