加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 建立一个在MVC路由之上做出反应的SPA

发布时间:2020-12-16 06:40:05 所属栏目:asp.Net 来源:网络整理
导读:我有一个由MVC管理的路由的API. 最重要的是,我想用反应建立一个SPA. 然而,我从我的反应应用程序内部构建的路由无法到达,我从ISS获得404,这里是我的代码中的存根. export default class Layout extends React.Component {render() { div Router history={ has
我有一个由MVC管理的路由的API.
最重要的是,我想用反应建立一个SPA.
然而,我从我的反应应用程序内部构建的路由无法到达,我从ISS获得404,这里是我的代码中的存根.

export default class Layout extends React.Component {
render() {
   <div> 
     <Router history={ hashHistory }>
       <Route path="/" component={ Home } >
         <Route path="login" component={ Login } />
       </Route>
     </Router>
   <div>
}

当我执行此代码作为独立的后端,它完美无缺.
有没有办法告诉MVC渲染设置URL的路由反应,让我们说“/ app / *”.

提前致谢.

解决方法

正如我在评论中提到的,我可能有一个适合您需求的解决方案.
该解决方案需要MVC控制器和相关的MapRoute().
一般的想法是使用控制器和cshtml通过MVC提供index.html页面,并在创建browserHistory时在react-router上配置一个基本名称.
这里的关键是basename值必须包含控制器名称的整个路径(没有域).
例如:
给这个控制器:

public class ReactController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

和cshtml:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8" />
    <title>app name</title>
    <link href="path/to/file.css/if/needed" rel="stylesheet" />
</head>
<body>
    <div id="app"></div>
    <script src="path/to/bundle.js"></script>
</body>
</html>

和路线地图:

routes.MapRoute(
        name: "reactApp",url: "react/{*pathInfo}",defaults: new { controller = "React",action = "Index",id = UrlParameter.Optional }
    );

现在,假设您的应用已在http://example.org/appName/下发布
那么你需要确保react-router在更改URL时不会删除URL的“appName”部分.
例如,如果您在主页 – http://example.org/appName/home
并且您转到关于页面,您希望react-router保留“appName”
像这样:http://example.org/appName/react/about
而不是这样http://example.org/about.

虽然这可以正常工作,因为您没有将此URL发布回服务器,但当您尝试直接转到“关于”页面时,您将遇到问题.当您使用以下URL发送请求时,服务器将返回404:http://example.org/about/
而不是这个:http://example.org/appName/react/about.

我对此问题的解决方法是将react-router包含一个基本名称,该名称包含appName子文件夹(如果有)控制器名称.

我正在使用useRouterHistory并创建browserHistory而不是从react-router导入它

const browserHistory = useRouterHistory(createHistory)({ 
  basename: appName
});

appName变量如下:

const controller = "/react";
const pathName = window.location.pathname;
const appName = pathName.substring(0,pathName.indexOf(controller) + controller.length);

这可以作为函数重构,但基本上它获取控制器名称的路径名(作为MVC应用程序的约定),包括控制器名称.这样,react-router将在每次更改URL时保留此路径.在我们的例子中“appName / react”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读