如何将 AppSettings 从 ASP.NET Core MVC Controller 传递到 ReactJS / Redux ClientApp?

How to pass AppSettings from ASP.NET Core MVC Controller to ReactJS / Redux ClientApp?

我想弄清楚如何从我的 AppSettings.json 获取 ApiUrl 设置到我的 ReactJS / Redux 状态。

我找到了以下文章,但是,它是针对 Angular 的。 https://elanderson.net/2017/10/pass-asp-net-core-appsettings-values-to-angular/

我能够使用该示例将我的 MVC 页面更改为:

@using Microsoft.Extensions.Configuration @inject IConfiguration Configuration @{ ViewData["Title"] = "Home Page"; }

<div id="react-app" asp-prerender-module="ClientApp/dist/main-server" asp-prerender-data='new { apiUrl = Configuration["ApiUrl"] }'>Loading...</div>

@section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}

这是我的 AppSettings.json:

{
  "ApiUrl": "http://localhost:55556/",
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

我想将 ApiUrl 参数从我的 AppSettings 发送到 ApplicationState 并从我的 ReactJS TypeScript 组件访问它。

我使用命令 dotnet new reactredux 创建了这个应用程序,我对 ReactJS 和 Redux 还很陌生。

花了一点时间才弄清楚,但这是解决方案。

  1. 如果您还没有为 Redux 创建 Reducer 来存储通用应用程序设置,请创建一个。这是我的 Reducer:

import {
  Action,
  Reducer
} from 'redux';

// -----------------
// STATE - This defines the type of data maintained in the Redux store.

export interface AppSettingsState {
  ApiUrl: string
}

// -----------------
// ACTIONS - These are serializable (hence replayable) descriptions of state transitions.
// They do not themselves have any side-effects; they just describe something that is going to happen.
// Use @typeName and isActionType for type detection that works even after serialization/deserialization.

export interface SetApiUrlAction {
  type: 'SET_APIURL';
  apiUrl: string
}

// Declare a 'discriminated union' type. This guarantees that all references to 'type' properties contain one of the
// declared type strings (and not any other arbitrary string).
type KnownAction = SetApiUrlAction;

// ----------------
// ACTION CREATORS - These are functions exposed to UI components that will trigger a state transition.
// They don't directly mutate state, but they can have external side-effects (such as loading data).

export const actionCreators = {
  setApiUrl: (url: string) => < SetApiUrlAction > {
    type: 'SET_APIURL',
    apiUrl: url
  }
};

// ----------------
// REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.

export const reducer: Reducer < AppSettingsState > = (state: AppSettingsState, incomingAction: Action) => {
  const action = incomingAction as KnownAction;

  switch (action.type) {
    case 'SET_APIURL':
      return {
        ApiUrl: action.apiUrl
      };
    default:
      // The following line guarantees that every action in the KnownAction union has been covered by a case above
      const exhaustiveCheck: never = action.type;
  }

  // For unrecognized actions (or in cases where actions have no effect), must return the existing state
  //  (or default initial state if none was supplied)
  return state || {
    ApiUrl: "http://localhost:5001/"
  };
};

  1. 创建减速器并将其挂接到 allReducers 列表后,您需要编辑 boot-server.tsx。在 boot-server 创建状态后,您可以发送任何您需要的东西。在这里,我从我在 MVC 视图中设置的 asp-prerender-data 标记中获取数据。

store.dispatch({ type: 'SET_APIURL', apiUrl: params.data.apiUrl });

这个其他答案对我有用,我只需要添加一个 const 服务 class 来读取这个值 How to push configuration values from Asp.Net Core MVC 2.0 config file to React TypeScript client script?

class ConfigService {
    Uri: string;

    public initialize(): void {
        if (this.Uri) return;
        var ell = document.getElementById('site-props');
        var jsontext = ell!.innerText;
        var siteProps = JSON.parse(jsontext);
        this.Uri = siteProps.Uri;
    } 
}

const configService = new ConfigService();
export default configService;