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
Related
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?}");
});
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);
}
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")]
I am attempting to change my start page in my ASP.NET Core MVC C# app. I want to first take the user to a login page and I have changed in the Startup.cs to this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Index}/{id?}");
}
}
and my controller looks like this
public class LoginController : Controller
{
public IActionResult Index()
{
return View();
}
}
And I have a page called Login.cshtml
What am I missing here?
This is my startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using eDrummond.Models;
namespace eDrummond
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<eDrummond_MVCContext>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opetions =>
{
options.LoginPath = "/Login/Index";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseCors(
options => options.AllowAnyOrigin()
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Index}/{id?}");
});
}
}
}
I am using VS2019 and created an asp.net core app, then selected MVC and all I've done is Scaffold Tables. SO the config should be correct?
You need to take regard of an authentication flow. First you are unauthorized. When you access any page where you aren't authorized you would like to REDIRECT to your login page, right? Then you need to tell this the program:
public void ConfigureServices(IServiceCollection services) {
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
// What kind of authentication you use? Here I just assume cookie authentication.
.AddCookie(options =>
{
options.LoginPath = "/Login/Index";
});
}
public void Configure(IApplicationBuilder app) {
// Add it but BEFORE app.UseEndpoints(..);
app.UseAuthentication();
}
Here is a stackoverflow topic, that addresses your problem:
ASP.NET core, change default redirect for unauthorized
Edit:
It turns out, that you can do something like this:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// You need to comment this out ..
// services.AddRazorPages();
// And need to write this instead:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Login/Index", "");
});
}
2. Edit:
So my first answer was not wrong, but it it did not included the changes to the controller it would need.
There are two solutions:
You add [Authorize] to all controller, you want to be authorized,
for example IndexModel (located in /Pages/Index.cshtml.cs) and when
entered, the program would see, the user is not authorized and would
redirect to /Login/Index (file located in
/Pages/Login/Index.cshtml.cs). Then you don't need to specify a DefaultPolicy or a FallbackPolicy (see source code below for FallbackPolicy reference)
You can make the program say, that all controller need to be
authorized even when not marked by [Authorize]. But then you need to
mark those controller you want pass without authorization with
[AllowAnonymous]. This is how it should be implemented then:
Structure:
/Pages
Index.cshtml
Index.cshtml.cs
/Login
Index.cshtml
Index.cshtml.cs
/Startup.cs
Files:
// File located in /Startup.cs:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;
namespace stackoverflow_aspnetcore_59448960
{
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)
{
// Does automatically collect all routes.
services.AddRazorPages();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// That will point to /Pages/Login.cshtml
options.LoginPath = "/Login/Index";
}); ;
services.AddAuthorization(options =>
{
// This says, that all pages need AUTHORIZATION. But when a controller,
// for example the login controller in Login.cshtml.cs, is tagged with
// [AllowAnonymous] then it is not in need of AUTHORIZATION. :)
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.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.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
// Defines default route behaviour.
endpoints.MapRazorPages();
});
}
}
}
// File located in /Pages/Login/Index.cshtml.cs:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace stackoverflow_aspnetcore_59448960.Pages.Login
{
// Very important
[AllowAnonymous]
// Another fact: The name of this Model, I mean "Index" need to be
// the same as the filename without extensions: Index[Model] == Index[.cshtml.cs]
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
// File located in /Pages/Index.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace stackoverflow_aspnetcore_59448960.Pages
{
// No [Authorize] needed, because of FallbackPolicy (see Startup.cs)
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
You should have folder structure as shown below.
Views
Login
Index.cshtml
It should take you to login page by default.
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");