Two projects in one solution - angularjs

I have two projects in my Visual Studio solution. One is an empty WEB API application with AngularJS and html front-end. Other is WEB API project with embedded database, controllers and stuff. The problem is when I call web api controllers from my first solution, I'm getting 404 not found. I suspect there is a problem in a hosting, but I don't know what kind exactly. I tried to host back-end project in IIS, but no results. Maybe there is something I missed.

After a lot time spent on investigating this, I realised that it was problem with different ports in localhost, the solution can be found there:http://jaliyaudagedara.blogspot.com/2014/08/angularjs-consuming-aspnet-web-api.html.
Basically I should change the project URL in properties to match the front-end project's localhost port and add an 'api' suffix to avoid using the same virtual directory by both projects.

#satish,
Global.asax:
namespace WebAPI_Training
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
WebApiConfig.cs:
namespace WebAPI_Training
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
}

Related

How to troubleshoot local SQL connections in a Blazor App from Visual Studio 2019

Learning Visual Studio 2019, C#, and SQL on my local PC. Having trouble connecting to the local SQL databases and making sure that my app opens up in my local browser.
Now an app that has previously worked fine gives me a 404 error. I cannot figure out why this is happening. In general I would like to have a tool or some other checklists to see why the server is throwing the error.
Would love to have some advice on best ways to do this.
=================
I should have added code and better explanation initially.
I am rebuilding an app. Started with a fresh Blazor server app project, and started moving things over from the old app. I was eventually able to compile the new app and then launched it and originally got an SQL error.
Now I can get the app to launch a browser window (tried both Chrome and Edge) but nothing displays at all, it just looks like it is loading. There is nothing I can see in the console or in output. No errors. When I debug everything seems fine, the code never hangs on any line. Nothing ever errors out.
I can rebuild again but I want to figure out how to troubleshoot issues like this.
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Wire_Desk.Data;
using Syncfusion.Blazor;
namespace Wire_Desk
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSyncfusionBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Wire_Desk
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
I don't know what more code I should include. When I debug once I get through the program file and step into, there are no more code to step through, although this was also true with a small sample app.
I am stumped.

Any Suggestions for getting ASP.NET Core + React Running on Elastic Beanstalk

I'm trying to get an ASP.NET Core with ReactJS application deployed to Amazon's Elastic Beanstalk. I've been using this tutorial to help me get started. I can deploy the tutorial (using the dotnet new web template) project just fine. However, when I publish a ASP.NET Core + React project (using dotnet new react template), I get the following exception when trying to access the application:
InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
Your application is running in Production mode, so make sure it has been published, or that you have built your SPA manually. Alternatively you may wish to switch to the Development environment.
This only occurs when I try to access ClientApp/ React components. When I access an API endpoint, there is no problem.
Additionally, this does not occur when running locally. Running locally works fine.
To reproduce this error, I've executed the following:
dotnet new react -o test-react/
dotnet publish test-react/ -o site/
cd site/
zip ../deploy.zip *
Finally, I manually import deploy.zip into AWS Elastic Beanstalk.
This is the Startup.cs file for that project.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
For reference, I am targeting .NET Core 3.1. Any ideas on how to solve this problem? I believe I've tried everything suggested on this GitHub issue. Any help would be greatly appreciated.
This question seems similar but is obviously for Angular and not React:
deploy Angular/Asp.Net Core 2.1 app to AWS: 500 error
It turns out that my deploy.zip package wasn't being created recursively so files in subdirectories were missing. Instead of doing,
zip ../deploy.zip *
I did,
zip -r ../deploy.zip *
which worked as intended. Silly me.

Spring-boot: add application to tomcat server

I have a back-end which is build on spring-boot and then some custom code from my school built upon that.
The front-end is pure angular application which I serve from a different server trough a gulp serve.
They're only connected by REST calls.
There's already an authentication module running on the backend and to now I need to serve this angular application from the same tomcat server the back-end is running on so it can also use this authentication module.
I've found this about multiple connectors so I copied it as following class to set up multiple connectors:
#ConfigurationProperties
public class TomcatConfiguration {
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
//tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat;
}
private Connector createSslConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = new ClassPathResource("keystore").getFile();
File truststore = new ClassPathResource("keystore").getFile();
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");
protocol.setTruststoreFile(truststore.getAbsolutePath());
protocol.setTruststorePass("changeit");
protocol.setKeyAlias("apitester");
return connector;
} catch (IOException ex) {
throw new IllegalStateException("can't access keystore: [" + "keystore"
+ "] or truststore: [" + "keystore" + "]", ex);
}
}
}
Problem is that I don't see or find how I should setup these connectors so they serve from my angularJS build folder.
Upon searching I came upon Spring-Boot : How can I add tomcat connectors to bind to controller but I'm not sure if in that solution I should change my current application or make a parent application for both applications.
My current application main looks like this:
#Configuration
#ComponentScan({"be.ugent.lca","be.ugent.sherpa.configuration"})
#EnableAutoConfiguration
#EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
If possible I'd like some more info about what connectors are in the spring-boot context.
If this is not the way to go I'd like someone to be able to conform this second solution or suggest a change in my code.
I'm really not sure enough about these solution that I want to go breaking my application over it. (though it's backed up with github)
Just place your AngularJS + other front-end assets into src/main/resources/static folder, Spring Boot will serve them automatically.

CORS issue with Angular Client and ASP.NET Web API

I have a client side application built with AngularJS that is consuming services from a RESTful ASP.NET Web API. So far so good. I have created both of them under the same solution on Visual Studio, the API is an ASP.NET project and the AngularJS is a website. Both projects have to work using windows authorization so I created the API with windows authorization as the default AA mechanism in the project creator wizard, and for the AngularJS I have enable windows authentication on the properties tab of the project.
In order to test the communication between the two applications I decided to build a simple service. I created a Quotation model class, built the controller for it, and then added migrations and added some quotations in the database. I then tried to send a get request from the angular application only to receive this error:
After studying this issue I realized that I had to enable CORS on the web API. So I went to NuGet Package Manager and added the Microsoft.AspNet.Cors package to the project.
I then enabled CORS on the WebApiConfig.cs like this:
namespace Web_API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
And I added the header to my controller class and method (just in case on the class wasn't enough):
namespace Web_API.Controllers
{
[EnableCors("*", "*","*")]
public class QuotationsController : ApiController
{
private Web_APIContext db = new Web_APIContext();
// GET: api/Quotations
[EnableCors("*", "*", "*")]
public IQueryable<Quotation> GetQuotations()
{
return db.Quotations;
}
However, I still get the same error when I make a get request from the AngularJS application. Does anyone know how to fix this issue?
can you please try this:
[EnableCors(origins: "*", headers: "*", methods: "*")]
Also don't use EnableCors in your method. As you've used this on your controller, by default all methods will fall under this rule.
I hope this will solve your problem. Thanks.

Spring MVC AngularJS No mapping found

I've been following the tutorial for integrating Spring Security with AngularJS, but it uses Spring Boot. I can get the tutorial examples working, but I need my app to run as a regular MVC application under Tomcat.
The problem is getting the application to route to the index.html page for the initial view. The only mappings I have in the controllers are the REST calls I want to receive from Angular, but I can't seem to get the application to go to the index page. Spring Boot does this automatically, but I'm going to run this as a web app under Tomcat. Trying to go there directly causes a 'No mapping found' error.
I'm using Java configuration and have the antMatchers, etc as described in the tutorial.
Here are a few entries in my config classes to make this happen.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers(HttpMethod.POST, "/user").permitAll().anyRequest()
.authenticated().and()
.csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
if ("true".equals(System.getProperty("httpsOnly"))) {
LOGGER.info("launching the application in HTTPS-only mode");
http.requiresChannel().anyRequest().requiresSecure();
}
}
#Configuration
#EnableWebMvc
#ComponentScan("com.mygroupnotifier.controller")
public class ServletContextConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/resources/static/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/resources/static/js/");
registry.addResourceHandler("/*.html").addResourceLocations("/resources/static/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
}
As usual the most difficult part of this is getting the leading and ending / on the classes and the html files.

Resources