How can I Access-Control-Allow-Origin on signalR C# angular5 - c#

I'm using angular 5 and C# API , and I'm trying to implement SignalR for push notifications ; and I'm stuck on this error "Access-Control-Allow-Origin"
I'm using ng-signalr on angular5
I did something wrong and i don't know where
startup.cs
using Owin;
using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.AspNet.SignalR;
namespace App5
{
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Enable attribute based routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{action}/{code}",
defaults: new { id = RouteParameter.Optional , action = RouteParameter.Optional, code = RouteParameter.Optional}
);
appBuilder.UseWebApi(config);
appBuilder.MapSignalR();
}
}
}
Ng2SignalRHub.cs
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App5
{
[Authorize]
[HubName("Ng2SignalRHub")]
public class Ng2SignalRHub : Hub
{
public override Task OnConnected()
{
Trace.TraceInformation("Ng2SignalRHub - OnConnected");
var user = GetAuthenticatedUser();
Clients.All.OnUserConnected(user);
return base.OnConnected();
}
private string GetAuthenticatedUser()
{
var username = Context.QueryString["user"];
if (string.IsNullOrWhiteSpace(username))
throw new System.Exception("Failed to authenticate user.");
Trace.TraceInformation("GetAuthenticatedUser :" + username);
return username;
}
}
}
Please can anyone has the solution for this issue
thanks in advance

Take a look at this link and see if it helps: https://github.com/aspnet/SignalR/issues/1400
Since SignalR is in preview with asp.net core 2.1 you have to make sure that all versions of the client packages match. You should also be configuring a CORS Policy
In ConfigureServices:
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:50000");
}));
services.AddSignalR();
In Configure:
app.UseCors("CorsPolicy");

Related

Owin Self-Hosting Web API With ASP.NET MVC Page

I created a Web API (Microsoft.AspNet.WebApi v5.2.7) targeted to .NET Framework 4.6.2 within a single project that included the default Help page MVC (Microsoft.AspNet.Mvc v5.2.7).
I created an ApiController to handle regular HTTP requests
using System.IO;
using System.Net;
using System.Threading;
using System.Web.Http;
using Project1.Models;
namespace Project1.Controllers
{
public class ProjectController : ApiController
{
// ... code ...
}
}
I eventually needed to self-host it in a Windows service. I was able to do this with OWIN (Microsoft.AspNet.WebApi.OwinSelfHost v5.2.9) by creating a second project, Project2, and adding Project1 as a reference in it. Project2 uses a startup like this
using System;
using System.Web.Http;
using Owin;
using Project1;
namespace Project2.Service
{
public class Startup
{
// reference controller so it's discoverable and can be used by service
Type projectControllerType = typeof(Project1.Controllers.ProjectController);
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
The service itself for Project2 is basic for this type of project. It starts and stop the web app disposable.
using System;
using System.ServiceProcess;
using Microsoft.Owin.Hosting;
namespace Project2.Service
{
public partial class Project2Service : ServiceBase
{
public string BaseAddress = "http://+:65432/";
private IDisposable _server = null;
public Project2Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_server = WebApp.Start<Startup>(url: BaseAddress);
}
protected override void OnStop()
{
if (_server != null)
{
_server.Dispose();
}
base.OnStop();
}
}
}
Now I wanted to add a /Help route, which comes with WebApi project in the Areas directory
Is there a way to implement this and make the help page callable from my self-hosted service?
I found in the Global.asax it calls AreaRegistration.RegisterAllAreas().
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Project1
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
I tried calling the AreaRegistration from the service startup
using System.Web.Mvc;
namespace Project2.Service
{
public class Startup
{
// reference controller so it's discoverable and can be used by service
Type projectControllerType = typeof(Project1.Controllers.ProjectController);
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
AreaRegistration.RegisterAllAreas();
appBuilder.UseWebApi(config);
}
}
}
This would cause an exception of This method cannot be called during the application's pre-start initialization phase.
I'm not sure how to go about this. Can I even implement pages with a self-hosted WebAPI?

ASP.NET Core 3.1 service.AddControllerWithViews not working as expected

I am trying to create a controller and my startup.cs is defined like this:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
namespace ConsoleApp1
{
public class Startup
{
public void ConfigurationServices(IServiceCollection service)
{
service.AddControllersWithViews();
// service.AddControllers(); tried adding this line did not work
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}
However on running the application, I am getting an error:
System.InvalidOperationException: 'Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddControllers' inside the call to 'ConfigureServices(...)' in the application startup code.'
Please help.
HomeController:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1.Controllers
{
public class HomeController : Controller
{
public string Index() // called action methods
{
return "Some string";
}
}
}
Please let me know if any additional details are required
since you are need controller with views, not api one, try this
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

How to resolve Method not found: 'System.Collections.Generic.IList`1<Microsoft.Extensions.FileProviders.IFileProvider> In .Net Core 3.1

I am facing below issue while migrating .Net Core 2.2 MVC project to 3.1 .
Method not found:
'System.Collections.Generic.IList`1<Microsoft.Extensions.FileProviders.IFileProvider>
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions.get_FileProviders()'.
Any Suggestions are welcome.
Below is the sample Code.
ConfigureServices Method.
services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{
options.FileProviders.Clear();
options.FileProviders.Add(new EmbeddedFileProvider(typeof(HomeController).GetType().Assembly));
});
services.AddControllersWithViews().AddRazorRuntimeCompilation();
Configure Method.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// Mapping of endpoints goes here:
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
Controller.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Let me know If further details are required.
You need the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package and these usings:
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation;
using Microsoft.Extensions.FileProviders;
You can also have the code something like this for ex:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.MvcRazorRuntimeCompilationOptions>(options =>
{
options.FileProviders.Add(
new EmbeddedFileProvider(typeof(HomeController).GetTypeInfo().Assembly));
});
// Requires using System.Reflection;
var assembly = typeof(HomeController).GetTypeInfo().Assembly;
services.AddMvc().AddRazorRuntimeCompilation()
.AddApplicationPart(assembly)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

Controller Method not found -AmbiguousActionException

I'm trying to call the httpget method of a controller.But its always 404.I have added all required directives.When i call the class name directly i get this exception
AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:
Controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebApplication2.Controllers
{
[Route("api/[controller]")]
public class ScannerController : Controller
{
[HttpGet]
public async Task<IActionResult> dostuff(string file_id)
{
return null;
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using WebApplication2.Models;
namespace WebApplication2
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// requires using Microsoft.Extensions.Options
services.Configure<DatabaseSettings>(
Configuration.GetSection(nameof(DatabaseSettings)));
services.AddSingleton<IDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
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.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
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.UseProxyToSpaDevelopmentServer("http://localhost:4200");
}
});
}
}
}
Change the route on the dostuff method to:
[HttpGet("dostuff")]

Using Stripe Checkout in a .net MVC Application

I'm trying to use Stripe Checkout to build my first MVC application, using the steps directly from Stripe found here - https://stripe.com/docs/checkout/aspnet
When I try and compile after following the steps, I receive the following errors...
Startup.cs
Error CS0103 The name 'StripeConfiguration' does not exist in the current context
HomeController.cs
Error CS0246 The type or namespace name 'ChargeCreateOptions' could not be found (are you missing a using directive or an assembly reference?)
Error CS0246 The type or namespace name 'CustomerCreateOptions' could not be found (are you missing a using directive or an assembly reference?)
Error CS0246 The type or namespace name 'ChargeService' could not be found (are you missing a using directive or an assembly reference?)
Error CS0246 The type or namespace name 'CustomerService' could not be found (are you missing a using directive or an assembly reference?)
I have already ensured I have the most recent Stripe Package using Tools>NuGet Package Manager>Manage NuGet Package for Solution.
HomeController.cs code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StripeCheckoutNPP.Models;
namespace StripeCheckoutNPP.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult Charge(string stripeEmail, string stripeToken)
{
var customers = new CustomerService();
var charges = new ChargeService();
var customer = customers.Create(new CustomerCreateOptions
{
Email = stripeEmail,
SourceToken = stripeToken
});
var charge = charges.Create(new ChargeCreateOptions
{
Amount = 500,
Description = "Sample Charge",
Currency = "usd",
CustomerId = customer.Id
});
return View();
}
}
}
Startup.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace StripeCheckoutNPP
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
StripeConfiguration.SetApiKey(Configuration.GetSection("Stripe")["SecretKey"]);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
In Visual Studio 2017 added .NET Core->ASP.NET Core Web Application named StripeCheckoutNPP. Version ASP.NET Core 2.2. Chose Web Application (Model-View-Controller). Unchecked Configure for HTTPS. Rebuilt project solution. Added Stripe.Net. stripe.net https://dashboard.stripe.com/login?redirect=%2Faccount%2Fapikeys
added my secretkey and publishkey to appsettings.json
Mine works even after the last answer post - doing your way.
It seems you are not nugeting correctly, so that the stripe namespaces and classes are not getting properly referenced.
I installed free JustDecompile, and saw that all your errors, for classes
StripeConfiguration
ChargeCreateOptions
CustomerCreateOptions
ChargeService
CustomerService
Are in the Stripe.net.dll
According to the instruction, your Configure method should be
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
StripeConfiguration.SetApiKey(Configuration.GetSection("Stripe")["SecretKey"]);
// the rest of the code....
}
Currently, you have the StripeConfiguration.SetApiKey() in the constructor

Categories