Reactjs 带有react模板的Asp.net核心web应用程序:在开发中,服务器首先检查mvc路由,但在产品中,服务器仅返回index.html
我正在尝试将一个使用razor页面的现有MVC应用程序迁移到WebAPI+ReactJS客户端。我正在一步一步地做这件事,这意味着我已经迁移了主页(主页/索引)以及其他一些页面/功能来做出反应。razor页面和react中实现的页面之间有链接。这在运行react development server的开发环境中非常有效 例如,在开发环境中,如果我路由到localhost:12345/Controller/Action(对于可用的控制器和操作),服务器将执行相应的操作并返回正确的视图,如果我尝试访问服务器未知的路由,它将返回index.html,react router将从此点开始处理路由。这是公认的行为,在开发环境中发挥着魅力 但当我构建react应用程序并在生产模式下运行应用程序时,情况会发生变化。请求从未到达服务器,而是由react路由器在客户端处理。当我硬刷新页面时,它会触发MVC操作 我希望在生产开发过程中有同样的表现 这就是starup.cs文件的外观Reactjs 带有react模板的Asp.net核心web应用程序:在开发中,服务器首先检查mvc路由,但在产品中,服务器仅返回index.html,reactjs,react-router,asp.net-core-mvc,asp.net-mvc-routing,create-react-app,Reactjs,React Router,Asp.net Core Mvc,Asp.net Mvc Routing,Create React App,我正在尝试将一个使用razor页面的现有MVC应用程序迁移到WebAPI+ReactJS客户端。我正在一步一步地做这件事,这意味着我已经迁移了主页(主页/索引)以及其他一些页面/功能来做出反应。razor页面和react中实现的页面之间有链接。这在运行react development server的开发环境中非常有效 例如,在开发环境中,如果我路由到localhost:12345/Controller/Action(对于可用的控制器和操作),服务器将执行相应的操作并返回正确的视图,如果我尝试访
// ConfigureServices
.
.
.
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ReactSource/build";
});
.
.
.
// Configure
.
.
.
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ReactSource";
// do not start the react development server in production
if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); }
});
.
.
你知道我错过了什么吗?我应该为此修改react路由器吗?我通过关闭(注销)create react应用程序开箱即用服务工作程序来解决问题,该工作程序试图缓存资产,并阻止请求到达服务器 在index.js文件中,我只是从“/registerServiceWorker”导入了
{unregister},并替换了registerServiceWorker()代码>使用注销()代码>在自动生成的index.js文件的末尾。要有一个Progress Web应用程序,您必须在React Web应用程序中启用Service worker
要在生产模式下解决缓存问题,必须在index.tsx文件中输入以下代码:
ReactDOM.render(
<BrowserRouter basename={baseUrl}>
<App />
</BrowserRouter>,
rootElement);
//index page is Route exact path.
if (window.location.href.includes('index'))
registerServiceWorker();
else
unregisterAndReload();
function unregisterAndReload() {
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
}
ReactDOM.render(
,
根元素);
//索引页是路由的精确路径。
if(window.location.href.includes('index'))
registerServiceWorker();
其他的
取消注册并加载();
函数unregisterAndReload(){
navigator.serviceWorker.ready.then(注册=>{
注册。注销()。然后(()=>{
window.location.reload();
});
});
}
和App.tsx文件应如下所示:
render() {
return (
<Layout>
<Route exact path='/index' component={Home} />
<Route path='/contact' component={ContactUs} />
</Layout>
);
}
render(){
返回(
);
}
当我硬刷新页面时,它会触发MVC操作,但已被接受。
使用Ctrl+F5进行硬刷新是什么意思?硬刷新后,代码是否工作正常?你能发布关于react路由器的相关代码来重现这个问题吗?此外,在MVC模板中,尝试设置默认控制器和操作,如模板:“{controller=Home}/{action=Index}”)代码>。