GraphQL for .NET core 3.1 - c#

I'm newbie in GraphQL for .NET core.
I Added GraphQL in my source but it not into controller when debug. It went to my ObjectGrapType
See the image detail :
Click start in GrapiQL
enter image description here
Then It not go to controller
enter image description here
3.It go to the Order Query
enter image description here
I don't understand why it happens
Can't you help me check that.
Is that an error or not?
My startUp class :
public void ConfigureServices(IServiceCollection services)
{
services.AddDiscoveryClient(Configuration);
services.AddCustomDbContext(Configuration);
services.AddControllers()
.AddNewtonsoftJson(o => o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
services.AddCustomSwagger();
services.AddCustomDependency(Configuration);
}
// 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();
}
app.UseDiscoveryClient();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseGraphiQl("/graphql");
app.UseRouting();
app.UseAuthorization();
app.UseGraphQL<OrderQuerySchema>();
app.UseGraphQLPlayground(options: new GraphQLPlaygroundOptions());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Thanks very much and have a good day
LamNV

Didn't get it. what lib do you use - GraphQL.Net?
Btw, based on GraphQL.net is existed a more elegant solution that allows starting much easier. You just have to define schemas in JSON file and set DB-connection string (NReco.GraphQL)

Related

c# SoapCore how to implement wildcard route

I'm using the SoapCore Nuget package to have a soap service on .Net Core. Below is the Configure method from Startup.cs that works great serving a Soap service. My challenge is that I want the service to be used with a service url that includes wildcards in the url path.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
app.UseSoapEndpoint<IpublishService>("/SoapService.asmx", new SoapEncoderOptions(), SoapSerializer.XmlSerializer);
}
The service works great in Postman using http://localhost:49154/SoapService.asmx but as I mentioned I would like to call it with wildcards like http://localhost:49154/AnyName1/AnyName2/SoapService.asmx
AnyName1 and AnyName2 can be any alpha text.
Thanks in advance for any suggestions.

SoapCore errors

I keep getting this issue when I attempt to visit the wsdl page for a service I created in .Net Core 3.0
The request reached the end of the pipeline without executing the endpoint: 'SoapCore'. Please register the EndpointMiddleware using 'IApplicationBuilder.UseEndpoints(...)' if using routing.
SoapCore version: 1.1.0.1-beta
I have also tried version 1.0.0 with the same result
Code:
Configure Services Function
services.AddControllers();
services.AddSoapCore();
services.TryAddSingleton<MyService>();
services.AddMvc();
Configure Function
if (env.IsDevelopment() || env.IsEnvironment("local"))
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.UseSoapEndpoint<MyService>("/Service.svc", new BasicHttpBinding(), SoapSerializer.DataContractSerializer);
endpoints.MapControllers();
});
It appears the the path is case sensitive. Sorry all, and if anyone is as aloof as me, make sure when visiting your route that you case it just as you have it in code.

Can I use Swashbuckle to generate Swagger UI from Blazor project c#

Can I use Swashbuckle to generate Swagger UI from project with Blazor C#
I know that swaschbuckle requires MVC and that you cannot have both of them in same project.
But is there any way around it.
I have resolved the issue by using the Balzor template for W ASP.Net core 3.0 application. And following this guide:Getting started with swashbuckle ASP.Net Core 3.0
I have used pre-release version 5.0.0-rc3 of Swashbuckle since version 4.0.1 failed at startup.
My startaup for anyone facing the same issue:
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.AddControllers();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
}
// 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();
app.UseDatabaseErrorPage();
}
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();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
Swagger is basically to expose your APIs on UI and if there is API controller concept then yes you can definitely use the swagger for blazor APIs....
Please go through the below URL and I am pretty sure that it will help you get what you want..
If you still facing any issue then please let me know I will try to give you an practical example of this...
https://www.talkingdotnet.com/create-a-crud-app-using-blazor-and-asp-net-core/

My SPA files are giving 404 errors when serving the SPA in a branch of the request pipeline. How do I make my static files available to my SPA?

First of, in my project root I have a folder called ClientApp, which contains a folder build which is where the output of my frontend build is located.
Then, in Startup.cs, I have the following in ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/build";
});
}
Following, my Configure method looks as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
app.Map("/dashboard", dashboard => {
dashboard.Use(async (context, next) => {
if (context.User.Identity.IsAuthenticated) {
await next();
return;
}
context.Response.Redirect("/Account/Login");
});
dashboard.UseSpa(spa => {
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment()) {
spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
}
});
});
}
If I remove the .Map(...) and just serve the spa in on the app IApplicationBuilder instance, then it works.
Thank you in advance for any help, this has been bugging me for a few days now.
Edit
The setup I would want in the end is as follows. /dashboard would serve a SPA application, and anyone accessing that route has to be authenticated. However, routes such as /Account/Login would not be part of the SPA.
By moving UseSpa outside of the Map, any routes that are not handled by the Mvc or a static file in wwwroot will render the SPA, but when visiting e.g. /about I want to show a 404, not the SPA which renders the 404.
Right, after some clarification and help from Edward, I was able to identify the problem. As Edward pointed out, since the call to UseSpa was done inside a branch of the request pipeline, the static assets which are served at ClientApp/build are not used since the request for those assets starts with /static/ and not /dashboard. This means the request pipeline is unaware of them.
The fix I found is actually more on the client build than the server, since I was unable to correctly let the server know about the static assets. The fix requires to set the homepage property in package.json as documented here. The only downside to this is that this does not work whilst running npm start since the build is not actually output to the filesystem but is instead in memory of the web-server.
On the server, I did have to move app.UseSpaStaticFiles() inside of the Map call in order for it to work correctly.
Thanks again to Edward for helping me better understand how Map works.
For app.Map, it will route the request based on path https://localhost:44378/dashboard/. Which means only requests with https://localhost:44378/dashboard/ will go into the Spa middleware.
For dashboard.UseSpa, it will survery spa static files with https://localhost:44378/styles.bundle.css which will not match https://localhost:44378/dashboard/.
If you did not want to change the request base path in SPA to https://localhost:44378/dashboard/, you may try move UseSpa outside of app.Map("/dashboard".
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
app.Map("/dashboard", dashboard =>
{
dashboard.Use(async (context, next) =>
{
if (context.User.Identity.IsAuthenticated)
{
await next();
return;
}
context.Response.Redirect("/Account/Login");
});
});
Update
For changing SPA Static files request URL, you could try to change package.json like below:
"start": "ng serve --base-href=/dashboard/ --serve-path=/ --live-reload-client=https://localhost:port/frontend/sockjs-node/",
For another option while developing, change code below in Startup
app.Map("/dashboard", frontendApp =>
{
frontendApp.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start -- --base-href=/frontend/ --serve-path=/ --live-reload-client=https://localhost:44302/frontend/sockjs-node/");
}
});
});

ASP.Net Core 1.1 - Angular2 project CSP not working

At the moment I'm using NWebsec.AspNetCore.Middleware nuget package to implement CSP headers. When simply creating a new ASP.NET Core 1.1 MVC Application and modifying the startup as followed, it's still possible to inject a script via the console. What am I missing?
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();
}
// 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.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseCsp(csp =>
{
csp.DefaultSources(src => src.Self());
});
}
}
The intension is to set CSP security to Angular2 generated static files (WebPack). But the CSP does not seem to be applied.
Middleware runs from top to bottom, this means that if a middleware exits early, then middlewares that are registered later in the pipeline will not run.
For example, you usually configure the static files middleware before the MVC middleware. That way, the application will first attempt to find a static file matching the current request and serve that directly (which will skip MVC). Only when there is no file, it will fall back to the MVC route lookup.
This ultimately means that everything that is there to secure stuff, or to lock users out of completing requests with “real” middleware (those that actually return stuff), has to be registered at the beginning of the pipeline.
In your case, you need to make sure that you call UseCsp() before UseMvc to make sure that the CSP middleware runs before the MVC middleware.

Categories

Resources