Cannot match any routes. URL Segment:ANGULAR/MAIN - c#

I'm trying to use Angular 6, angular CLI and MV Areas.For POC reasons I've named it Angular The idea was to have an angular app per Area. If this is a bad idea please let me know because maybe the whole concept is And for me it's a pain. This is the first time that I'm configuring it. Below is my example Area has a main controller which looks like this:
public class MainController : BaseController
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
And my Route config looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "mvc",
url: "{controller}/{action}/",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// This is a catch-all for when no other routes match the request; let the Angular 2 router take care of it...
routes.MapRoute(
name: "default",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" } // The view that bootstraps Angular 2 app
);
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
I have my app folder in the main project directory, aslo files like angular.json and packages.json. I've created this using angular CLI
Below is an angular.josn file:
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "eagle-app",
"projects": {
"test-app": {
"root": "test-app/",
"sourceRoot": "test-app",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "eagle-app/dist/test-app",
"index": "Areas/ANGULAR/Views/Main/Index.cshtml",
"main": "eagle-app/test-app/main.ts",
"polyfills": "eagle-app/test-app/polyfills.ts",
"tsConfig": "eagle-app/test-app/tsconfig.app.json",
"assets": [
"test-app/favicon.ico",
"test-app/assets"
],
"styles": [
"eagle-app/test-app/styles.css",
"node_modules/primeicons/primeicons.css",
"node_modules/primeng/resources/themes/nova-light/theme.css",
"node_modules/primeng/resources/primeng.min.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "eagle-app/test-app/environments/environment.ts",
"with": "eagle-app/test-app/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "test-app:build"
},
"configurations": {
"production": {
"browserTarget": "test-app:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "test-app:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "eagle-app/test-app/test.ts",
"polyfills": "eagle-app/test-app/polyfills.ts",
"tsConfig": "eagle-app/test-app/tsconfig.spec.json",
"karmaConfig": "eagle-app/test-app/karma.conf.js",
"styles": [
"eagle-app/test-app/styles.css",
"node_modules/primeicons/primeicons.css",
"node_modules/primeng/resources/themes/nova-light/theme.css",
"node_modules/primeng/resources/primeng.min.css"
],
"scripts": [],
"assets": [
"test-app/favicon.ico",
"test-app/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"eagle-app/test-app/tsconfig.app.json",
"eagle-app/test-app/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"test-app-e2e": {
"root": "test-app-e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "test-app-e2e/protractor.conf.js",
"devServerTarget": "test-app:serve"
},
"configurations": {
"production": {
"devServerTarget": "test-app:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "test-app-e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
}
}
My Index.cshtml from the Area looks like this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TestApp</title>
<base href="/Areas/ANGULAR/Main/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<test-app>
</test-app>
#section scripts {
#Scripts.Render("~/Content/angular-ui")
}
</body>
</html>
As you can see I have an routingcomponent which looks like this:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { Sub1Component } from "./submodule1/sub1.component"
import { Sub2Component } from "./submodule2/sub2.component"
import { AppComponent } from "./app.component";
const routes: Routes = [
{ path: 'Sub1', component: Sub1Component },
{ path: 'Sub2', component: Sub2Component },
{
path: '',
redirectTo: '/Sub1',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
I'm injecting this to my app.component which a loop that creates buttons for submodules like defined above and the view for it is in shared foler. The problem is I'm getting error like below. And I can't get seem to have the default route for sub1 to be loaded.
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'ANGULAR/Main'
Error: Cannot match any routes. URL Segment: 'ANGULAR/Main'
at ApplyRedirects.push.../node_modules/#angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:1382)
at CatchSubscriber.selector (router.js:1363)
at CatchSubscriber.push.../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at TapSubscriber.push.../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:61)
at ApplyRedirects.push.../node_modules/#angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:1382)
at CatchSubscriber.selector (router.js:1363)
at CatchSubscriber.push.../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:83)
at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:61)
at TapSubscriber.push.../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:61)
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at zone.js:873
at ZoneDelegate.push.../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3815)
at ZoneDelegate.push.../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push.../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
Anyway I have also a general question is the concept of having seperate apps for an Area is ok? Or maybe some of you have any experience with angular CLI, MVC5 Areas and Angular6? How it should be done. Thanks for you patience and help in advance. Below also are print screens how I have my project structured

Ok with a help of a friend in my team we've managed to solve the issue! The thing is in our MVC app we have also a angularjs (1.x) app and we've noticed that we have hash based urls. That lead us to finding the answer, that in our app module we should import this:
{ provide: LocationStrategy, useClass: HashLocationStrategy }
which get's imported from:
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
in the this looks like this:
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
, BrowserAnimationsModule
, HttpClientModule
, FormsModule
, SharedModule
, AppRoutingModule
],
providers: { provide: LocationStrategy, useClass: HashLocationStrategy }],
bootstrap: [AppComponent]
})
Also we had to delele the html part because we had sort of html in html. That his instead of having this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TestApp</title>
<base href="/Areas/ANGULAR/Main/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<test-app>
</test-app>
#section scripts {
#Scripts.Render("~/Content/angular-ui")
}
</body>
We should have only this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Styles.Render("~/Content/prime-ng-css")
<div id="test-app">
<test-app>
</test-app>
</div>
#section scripts {
#Scripts.Render("~/Content/mMonitor-ui")
}
This was the solustion for the problem i this specific case and config that we have

Related

Blazor WebAssembly Hosted on IIS - only API is working

I have a project where I have developed a solution with Blazor WebAssembly Hosted model. I have a Server Project, a Client project and a Shared project (but I renamed it to Domain).
When I publish, I publish to a folder because I have no other ways of connecting to the server I try to deploy to, which is of Windows Server 2019 OS.
Then I add the published folder to IIS but I can only get the API endpoints working. When I navigate to the root of the application, i.e. https:/localhost:5001 I just get a 404 error.
I have installed dependencies for .NET, URL Rewrite, added a self-signed certificate etc.
I can't understand why this doesn't work. When I launch in Visual Studio it works perfectly fine both with Release and Debug flags.
Can someone guide me to what I might have done wrong?
Log when navigating to https://localhost:5001 (not working)
[10:11:24 Information] Microsoft.Hosting.Lifetime Application started.
Press Ctrl+C to shut down.
[10:11:24 Information] Microsoft.Hosting.Lifetime Hosting environment:
Production
[10:11:24 Information] Microsoft.Hosting.Lifetime Content root path:
C:\Temp\Project\publish
[10:11:24 Information] Microsoft.AspNetCore.Hosting.Diagnostics
Request starting HTTP/2 GET https://localhost:5001/ - -
[10:11:25 Information] Microsoft.AspNetCore.Routing.EndpointMiddleware
Executing endpoint 'Fallback {*path:nonfile}'
[10:11:25 Information] Microsoft.AspNetCore.Routing.EndpointMiddleware
Executed endpoint 'Fallback {*path:nonfile}'
[10:11:25 Information] Microsoft.AspNetCore.Hosting.Diagnostics
Request finished HTTP/2 GET https://localhost:5001/ - - - 404 - -
94.7963ms
Log when navigating to https://localhost:5001/api/dataflows (works)
[10:12:46 Information] Microsoft.AspNetCore.Hosting.Diagnostics
Request starting HTTP/2 GET https://localhost:5001/api/dataflows - -
[10:12:47 Information] Microsoft.AspNetCore.Routing.EndpointMiddleware
Executed endpoint
'Project.Web.Server.Controllers.DataflowsController.GetDataflows
(Project.Web.Server)'
[10:12:47 Information] Microsoft.AspNetCore.Hosting.Diagnostics
Request finished HTTP/2 GET https://localhost:5001/api/dataflows - - -
200 2 application/json;+charset=utf-8 619.7714ms
Project.Web.Server/Statup.cs: ConfigureServices
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("{*path:nonfile}", "index.html"); ;
});
}
Project.Web.Server/appsettings.json
{
"AllowedHosts": "*",
"ConnectionStrings": {
"Identity": "Data Source=|DataDirectory|\\IdentityDB.db",
"Api": "Data Source=|DataDirectory|\\ApiDB.db",
"Dataflows": "Data Source=|DataDirectory|\\DataflowsDB.db"
},
"IdentityServer": {
"Clients": {
"Project.Web.Client": {
"Profile": "IdentityServerSPA"
}
},
"Key": {
"Type": "Store",
"StoreName": "My",
"StoreLocation": "CurrentUser",
"Name": "CN=localhost"
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Temp\\Project\\log.txt",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}"
}
}
],
"Enrich": [ "FromLogContext", "WithExceptionDetails" ]
}
}
Project.Web.Client/Program.cs: ConfigureServices
public static Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddHttpClient("Project.Web.Client.API", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("Project.Web.Client.API"));
// Add Open ID Connect client settings
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("oidc", options.ProviderOptions);
}).AddAccountClaimsPrincipalFactory<RolesClaimsPrincipalFactory>();
builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();
builder.Services.AddApiAuthorization();
return builder.Build().RunAsync();
}
Project.Web.Client/Shared/RedirectToLogin.razor
#inject NavigationManager Navigation
#code {
protected override void OnInitialized()
{
Navigation.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(Navigation.Uri)}");
}
}
Project.Web.Client/wwwroot/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Project.Web</title>
<base href="/" />
<link href="/company/fonts/css/styles-technical.css" rel="stylesheet" />
<link href="/company/icons/css/styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script type="module">
import { defineCustomElements } from '/company/web-ui/loader/index.js';
defineCustomElements(window);
</script>
<script src="/scripts/utils.js"></script>
</body>
</html>
Project.Web.Client/wwwroot/appsettings.json
{
"oidc": {
"Authority": "https://localhost:5001/",
"ClientId": "Project.Web.Client",
"ResponseType": "code",
"DefaultScopes": [
"openid",
"profile"
],
"PostLogoutRedirectUri": "/",
"RedirectUri": "https://localhost:5001/authentication/login-callback"
}
}
Make sure you install the .Net core hosting bundle on your server.
https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-6.0.3-windows-hosting-bundle-installer

How to render prettified JSON in C# Razor templates?

I am trying to render formatted JSON as HTML using Razor Templates.
I am currently trying to do it like this:
<div>
<pre>
#JsonHelper.SerializeObject(item.AttributeValue, new Newtonsoft.Json.JsonSerializerSettings() {
Formatting = Newtonsoft.Json.Formatting.Indented })
</pre>
</div>
But once it gets to the browser, it is all on one line and looks something like this:
"{\"FieldA\":[{\"FieldAName\":\"start\",\"startValue\":\"startValue2\"},{\"FieldB\":\"FieldBsub\",\"FieldBValue\":\"SomeField\",\"Options\":[{\"ANumber\":1,\"Option\":\"LOL\"},{\"ANumber2\":2,\"Option\":\"LMAO\"},{\"ANumber3\":3,\"Option\":\"OTHER\"},{\"ANumber\":4,\"Option\":\"ROFL\"},{\"ANumber\":5,\"Option\":\"ROFL\"}]}],\"Choice\":\"yes\",\"fieldC\":\"yes\"}"
I am assuming the backslashes should be breaks that should be formatting it?
I am new to C# and I am pretty sure there is something wrong with the JSonHelper method? Maybe it is already a string?
Anyways I would like it to display like a formatted JSON in the browser view like this:
Just an example:
[
{
"_id": "5deeea2ed84c28fb633ecac8",
"index": 0,
"guid": "accc7f31-bfc7-4a42-9d76-a6f9f71e6f87",
"tags": [
"proident",
"aute",
"pariatur",
"cupidatat",
"officia",
"adipisicing",
"dolor"
],
"friends": [
{
"id": 0,
"name": "Alyson Scott"
},
{
"id": 1,
"name": "Ratliff Castaneda"
},
{
"id": 2,
"name": "Bernice Lester"
}
],
"greeting": "Hello, undefined! You have 6 unread messages.",
"favoriteFruit": "banana"
}
]
I have a string property in my model that I set to a formatted JSON string
public string PortfolioJson { get; set; }
public async Task<IActionResult> OnGetAsync(int? rid) {
PortfolioJson = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented);
}
Then on the page I just output that. I also use a JS library to pretty print the JSON.
#section Styles {
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/default.min.css" />
}
<div class="row">
<pre>
<code class="json">
#Model.PortfolioJson
</code>
</pre>
</div>
#section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script>
<script>
hljs.initHighlightingOnLoad();
</script>
}

how to remove text after "localhost" in browser?

I am new in MVC. I have tested my site in debug mode. So far there is no problem. But when i deploy it to my localhost i am having an issues "POST http://localhost/Home/GetEnumerationList 404 (Not Found)". It looks like it failed to call the action in controller. When i look at the address it shows like this "http://localhost/mymvcsite" instead of like this "http://localhost". I have also test using Postman, when i run post as this "http://localhost/mymvcsite/Home/GetEnumerationList" only then i will get the result.
Is there a way i can set up my iis to remove "mymvcsite" from "http://localhost/mymvcsite"?
Here is the JQuery to call the Action in Controller.
<script>
var popup, dataTable;
$(document).ready(function () {
dataTable = $("#batchTable").DataTable({
"ajax": {
"url": "/Home/GetEnumerationList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "EnumType", "name":"EnumType" },
{ "data": "EnumValue", "name": "EnumValue" },
{ "data": "EnumText", "name": "EnumText" },
{ "data": "IsDeleted", "name": "IsDeleted" },
{
"data": "EnumId", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit","Home")/" + data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left: 5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
},
],
"processing": "true",
"serverSide": "true",
"order": [0, "asc"]
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Add Enum",
height: 470,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm("Are you sure you want to delete this data?")) {
$.ajax({
type: "POST",
url: '#Url.Action("DeleteEnum", "Home")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
}
)
}
}
</script>
Hopefully someone can please guide me on this.
You might need to set the default route mapped to your mymvcsite at your backend.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "mymvcsite", action = "Index", id = UrlParameter.Optional }
);
Instead of add the site as virtual directory of "Default Web Site", i add new website and point it to my webroot physical path. I hope this helps anyone in the future.

ASP.Net Core: Setting up React.js + webpack + babel in VS2017

After some playing around with ReactJS (which was running on webpack-server), decided to try ASP.Net Core project in Visual Studio 2017.
I created empty ASP.Net Core project.
Removed all stuff in
wwwroot and stuff related to bower.
Removed all controllers
except Home and removed views except Home/Index.cshtml
Added
webpack.config.js, package.json and .babelrc
Installed Asp.React from Nuget
My package:
{
"name": "TrainDiary",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"css-loader": "^0.28.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"style-loader": "^0.18.2"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"html-webpack-plugin": "^2.29.0",
"clean-webpack-plugin": "^0.1.16",
"style-loader": "^0.18.2",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"-vs-binding": {
"BeforeBuild": [
"build"
]
}
}
My webpack config:
var CleanWebpackPlugin = require('clean-webpack-plugin');
let path = require('path');
const bundleFolder = "wwwroot/build/";
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: path.resolve(__dirname, 'Scripts/app/index.html'),
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: path.resolve(__dirname, 'Scripts/app/Core/app.js'),
module:{
loaders:[
{
test: /\.js$/,
exclude: [/node_modules/],
loader: 'babel-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
},
output:{
filename: 'index.js',
path: path.resolve(__dirname, bundleFolder)
},
stats: {
colors: true,
modules: true,
reasons: true,
errorDetails: true
},
plugins: [ new CleanWebpackPlugin([bundleFolder]), HTMLWebpackPluginConfig]
};
babelrc is simple like that { presets:['react'] }
So, when I run npm run build everything is fine, in wwwroot it generates index.js and index.html as well.
But nothing happens when I run my application! I mean nothing at all. Blank white page. No error in console. Just like that.
Also, here is my Startup.cs:
namespace TrainDiary.Web
{
using React.AspNet;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddLogging();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddReact();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseReact(config =>
{ });
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
HomeController:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Home/Index.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
</head>
<body>
<!-- Load all required scripts (React + the site's scripts) -->
#Html.Partial("~/wwwroot/build/index.html")
</body>
</html>
How come? What's wrong with this approach?
UPD:
entrance point index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/Core/app.js'
ReactDOM.render(
<App />,
document.getElementById("content")
);
Core/app.js is here
import React from 'react';
import ReactDOM from 'react-dom';
export default class App extends React.Component {
render() {
return (
<div>
Hello, React!
</div>
)
}
}
index.html which we try to render in Index.cshtml
<body>
<div id='content'></div>
</body>
Screenshot of the rendered stuff:
UPD2:
As Jose advised - changed Index.cshtml like that:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
<script src="~/build/index.js"></script>
</head>
<body>
<!-- Load all required scripts (React + the site's scripts) -->
<div id='content'></div>
</body>
</html>
and removed webpack-html-plugin.
Thats what I got now (css-loader worked btw):
UPD3:
Fixed some wrong stuff in webpack.config (entry point), but still no success:
var CleanWebpackPlugin = require('clean-webpack-plugin');
let path = require('path');
const bundleFolder = "wwwroot/build/";
module.exports = {
entry:'./Scripts/index.js',
module:{
loaders:[
{
test: /\.js$/,
exclude: [/node_modules/],
loader: 'babel-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
},
output:{
filename: 'index.js',
path: path.resolve(__dirname, bundleFolder)
},
stats: {
colors: true,
modules: true,
reasons: true,
errorDetails: true
},
plugins: [ new CleanWebpackPlugin([bundleFolder])]
};
UPD4:
Now it works! In previous case I just didn't pay attention to debugger console with error like described here.
So I changed Index.cshtml like that:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
</head>
<body>
<!-- Load all required scripts (React + the site's scripts) -->
<div id='content'></div>
<script src="~/build/index.js"></script>
</body>
</html>
And now it's fine!
Summary of comments' suggestions:
Make sure is being render in your app code
Remove HTMLWebpackPlugin and change Index.cshtml to include bundle.js ( the partial view in your mvc view is loading a full template by using html wepack plugin)
Glad to help you!

swagger-codegen - How do I supply a body to the generated C# SDK method?

I'm using the (unofficial) swagger-codegen-cli Docker container from https://hub.docker.com/r/jimschubert/swagger-codegen-cli/ which pulls swagger-codegen from the master branch before it runs. I tried grabbing the recently documented (official) swagger-codegen-cli from https://hub.docker.com/r/swaggerapi/swagger-codegen-cli/, but it appears to be unavailable at the moment.
As it stands with the unofficial cli, I have generated a C# SDK from swagger documentation that contains the following:
/api/customer/{zoneId}/files/cover/gallery: {
get: {
tags: [
"FileUpload"
],
summary: "Get all files in customer cover gallery",
operationId: "FileUpload_GetCustomerCoverFiles",
consumes: [ ],
produces: [
"application/json",
"text/json"
],
parameters: [
{
name: "zoneId",
in: "path",
description: "",
required: true,
type: "integer",
format: "int32"
}
],
responses: {
200: {
description: "OK",
schema: {
type: "array",
items: {
$ref: "#/definitions/FileUploadGalleryItemModel"
}
}
}
}
},
post: {
tags: [
"FileUpload"
],
summary: "Upload file to customer cover gallery",
operationId: "FileUpload_CreateCustomerCoverGalleryItem",
consumes: [
"application/octet-stream"
],
produces: [
"application/json",
"text/json"
],
parameters: [
{
name: "zoneId",
in: "path",
description: "",
required: true,
type: "integer",
format: "int32"
},
{
name: "payload",
in: "body",
description: "",
required: true,
type: "byte[]",
format: "binary"
}
],
responses: {
200: {
description: "OK",
schema: {
type: "array",
items: {
$ref: "#/definitions/FileUploadGalleryItemModel"
}
}
}
}
}
},
The 'payload' is provided within the body of the request, however I don't see any way to provide the body to the method generated within the SDK with the following signature: public List<FileUploadGalleryItemModel> FileUploadCreateCustomerCoverGalleryItem (int? zoneId).
Any suggestions on what I might be overlooking or doing incorrectly?
You can document payload as file (form parameter) instead, e.g. https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml#L269-L273, and you will find sample code in the auto-generated documentation (please take a look at the auto-generated README.md as a starting point)

Categories