Core: Targeting .NET Core 2.1 - Startup error for new Aurelia WebApp - JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

Created on 25 Jun 2018  Â·  12Comments  Â·  Source: dotnet/core

Targeting .NET Core 2.1 - Startup error for new Aurelia WebApp

JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

  • Operating System: Windows 10
  • .NET Core SDK Versions: 2.1.201 / 2.1.301
  • VS2017 / VS Code
  • NPM: 6.1.0
  • Node: 8.11.3

I´m not sure if this issue is related to .NET Core 2.1 but I will try to get some information.

I set up a new aurelia web project:

dotnet new web
au new

If I´m targeting framework .NET Core 2.0 with NuGet-Package "Microsoft.AspNetcore.All" version 2.0.6 everything works fine:

<PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
  </PropertyGroup>
<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" />
  </ItemGroup>

As soon as I update the target framework to 2.1 I´ve got the startup issue:

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
  </ItemGroup>

By calling UseWebpackDevMiddleware a JSON-Object will be parsed and throws following error message:

JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

It sounds like where there should be a json object returned an error (html error page) were returned and cause this issue. But I am not able to find out which json object will be loaded or is missing!?

```c#
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ConfigFile = "webpack.netcore.config.js",
HotModuleReplacementClientOptions = new Dictionary{
{"reload", "true"}
}
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
}

I allready tried to reinstall VS2017 / Node.js / .NET Core SDKs without success.

The initial test project is linked here:
[example project respository](https://github.com/Melfi11/example-project-netcore2.1-aurelia)

Attached my **webpack.config.js**...

```js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { ProvidePlugin } = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
  condition ? ensureArray(config) : ensureArray(negativeConfig);

// primary config:
const title = 'Aurelia Navigation Skeleton';
const outDir = path.resolve(__dirname, project.platform.output);
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';

const cssRules = [
  { loader: 'css-loader' },
];

module.exports = ({production, server, extractCss, coverage, analyze} = {}) => ({
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [srcDir, 'node_modules'],
  },
  entry: {
    app: ['aurelia-bootstrapper'],
    vendor: ['bluebird'],
  },
  mode: production ? 'production' : 'development',
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
    sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
    chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
  },
  performance: { hints: false },
  devServer: {
    contentBase: outDir,
    // serve index.html for all 404 (required for push-state)
    historyApiFallback: true
  },
  devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map',
  module: {
    rules: [
      // CSS required in JS/TS files should use the style-loader that auto-injects it into the website
      // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: cssRules
        }) : ['style-loader', ...cssRules],
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
        issuer: /\.[tj]s$/i
      },
      {
        test: /\.scss$/,
        use: ['css-loader', 'sass-loader'],
        issuer: /\.html?$/i
      },
      { test: /\.html$/i, loader: 'html-loader' },
      { test: /\.tsx?$/, loader: "ts-loader" },
      { test: /\.json$/i, loader: 'json-loader' },
      // use Bluebird as the global Promise implementation:
      { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
      // embed small images and fonts as Data Urls and larger ones as files:
      { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
      { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
      { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
      // load these fonts normally, as files:
      { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
      ...when(coverage, {
        test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
        include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
        enforce: 'post', options: { esModules: true },
      })
    ]
  },
  plugins: [
    new AureliaPlugin(),
    new ProvidePlugin({
      'Promise': 'bluebird'
    }),
    new ModuleDependenciesPlugin({
      'aurelia-testing': [ './compile-spy', './view-spy' ]
    }),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      minify: production ? {
        removeComments: true,
        collapseWhitespace: true,
        collapseInlineTagWhitespace: true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes: true,
        minifyCSS: true,
        minifyJS: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        ignoreCustomFragments: [/\${.*?}/g]
      } : undefined,
      metadata: {
        // available in index.ejs //
        title, server, baseUrl
      }
    }),
    ...when(extractCss, new ExtractTextPlugin({
      filename: production ? '[contenthash].css' : '[id].css',
      allChunks: true
    })),
    ...when(production, new CopyWebpackPlugin([
      { from: 'static/favicon.ico', to: 'favicon.ico' }])),
    ...when(analyze, new BundleAnalyzerPlugin())
  ]
});

... and the webpack.netcore.config.js:

const webpackConfig = require('./webpack.config');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
var originalConfig = webpackConfig({});

module.exports = () => {
  let config = originalConfig;
  // output files without hashes
  config.output.filename = '[name].bundle.js';
  config.plugins.splice(config.plugins.indexOf(HtmlWebpackPlugin));
  // fix output path for .net core development
  config.module.rules = config.module.rules.map(x => {
    if (x.loader && (x.loader === 'url-loader' || x.loader === 'file-loader')) {
      if (!x.options) {
        x.options = {};
      }
      x.options.publicPath = project.platform.output.replace('wwwroot', '') + '/';
    }
    return x;
  });
  config.plugins = [
    // first clean the output directory
    new CleanWebpackPlugin([config.output.path]),
    ...config.plugins
  ];

  return config;
};

Most helpful comment

Unfortunately it was neccessary to use a upper case "U" at "UseSocketsHttpHandler".
It seems to work with following Main() and active proxy:

```c#
public static void Main(string[] args) {
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
CreateWebHostBuilder(args).Build().Run();
}

All 12 comments

To be clear, the repro steps are cloning the repo, npm install and dotnet run? if I remove the app.Run(…) thing from the startup the app kind of works..
btw in 2.1, you should remove the Version="…" attribute from the package reference to Microsoft.AspNetCore.All and .App. The tooling will choose an appropriate version.

Yes that´s correct!
Do you have a difference to my operating system settings? (Node.js or something else!?)

Thanks for information - I removed the version for package Microsoft.AspNetCore.All.

@Melfi11 It seems, that the internal call to node is intercepted somehow.
Try to disable your proxy if there is one.

Thanks a lot @road42 - without the proxy settings I can run the application. But why it´s been crashing with active proxy? Targetting .NET Core 2.0 it works well!?

I‘ve had a look on the source and the extension seems to use the default HttpClient without any new factory methods or something like that.

There's a new implementation for the handler behind HttpClient in 2.1, can you try adding this before anything else in your Main() method and see if the behavior changes?:

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

If so, this may be a bug with the new managed http client handler.

Unfortunately it was neccessary to use a upper case "U" at "UseSocketsHttpHandler".
It seems to work with following Main() and active proxy:

```c#
public static void Main(string[] args) {
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
CreateWebHostBuilder(args).Build().Run();
}

The "u" has to be uppercase

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

See: source

@stephentoub @karelz could one of you maybe help direct this issue? are there known issues with proxies and the new handler?

Moving to corefx

Issue moved to dotnet/corefx #30962 via ZenHub

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Rand-Random picture Rand-Random  Â·  4Comments

zuosc picture zuosc  Â·  3Comments

mmacneil picture mmacneil  Â·  3Comments

sravan1022 picture sravan1022  Â·  4Comments

AxxlForce picture AxxlForce  Â·  3Comments