【问题标题】:Why am I receiving a 404 error during Stripe Web Hook Test为什么我在 Stripe Web Hook 测试期间收到 404 错误
【发布时间】:2020-04-10 02:31:29
【问题描述】:

我在 Stripe https://www.websitename.com/StripeWebHook/Index 创建了一个端点,但是当我测试它时,我得到一个 404 错误(也尝试了没有索引的端点)。在 StripeWebHook 类的示例代码中,它表示将其标记为 api。 [Route("api/[controller]")] 公共类 StripeWebHook : 控制器。我是否在启动/程序文件中遗漏了某些内容,或者我是否错误地调用了索引?

启动类

namespace MyNameSpace
{
    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.AddDbContext<Models.CContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));



            services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<CContext>();

            //added this to fix CarRepository error
            services.AddScoped<ICartRepository, CartRepository>();


            services.AddSession();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


        }


        // 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();
                app.UseExceptionHandler(errorApp =>//This whole thing is random exception stuff
                {
                    errorApp.Run(async context =>
                    {
                        context.Response.StatusCode = 500;
                        context.Response.ContentType = "text/html";

                        await context.Response.WriteAsync("<html lang=\"en\"><body>\r\n");
                        await context.Response.WriteAsync("ERROR!<br><br>\r\n");

                        var exceptionHandlerPathFeature =
                            context.Features.Get<IExceptionHandlerPathFeature>();

                        // Use exceptionHandlerPathFeature to process the exception (for example, 
                        // logging), but do NOT expose sensitive error information directly to 
                        // the client.

                        if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
                        {
                            await context.Response.WriteAsync("File error thrown!<br><br>\r\n");
                        }

                        await context.Response.WriteAsync("<a href=\"/\">Home</a><br>\r\n");
                        await context.Response.WriteAsync("</body></html>\r\n");
                        await context.Response.WriteAsync(new string(' ', 512)); // IE padding
                    });
                    app.UseDatabaseErrorPage();
                });
                }
            else
            {
                app.UseExceptionHandler("/Home/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.UseCookiePolicy();

            app.UseSession();
            app.UseAuthentication();

            app.UseMvc(routes =>
            {

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            //app.UseStaticFiles();

            // This will add "Libs" as another valid static content location


        }
    }
}

控制器类

namespace MyNameSpace.Controllers
{


   [Route("api/[controller]")]
    public class StripeWebHook : Controller
    {
        // You can find your endpoint's secret in your webhook settings
        const string secret = "whsec_....";

        [HttpPost]
        public async Task<IActionResult> Index()
        {
            StripeConfiguration.ApiKey = "sk_test_....";
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json,
                    Request.Headers["Stripe-Signature"], secret);
                // Handle the checkout.session.completed event
                if (stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    var session = stripeEvent.Data.Object as Stripe.Checkout.Session;

                    // Fulfill the purchase...
                    //HandleCheckoutSession(session);
                }
                else
                {
                    return Ok();
                };
                return Ok();
            }
            catch (StripeException e)
            {
                return BadRequest();
            }
        }
    }
}

【问题讨论】:

  • 如果我的回答没有解决您的问题,请添加您的 statup.cs 类的代码。
  • 请分享有关该问题的 startup.cs 和 StripeWebHook 控制器。它将帮助我们了解您的路线是如何配置的。
  • 我认为问题在于我测试了错误的文件,所以当 api 路由在那里时,它使用 website/api/stripwebhook/index 工作

标签: api asp.net-core stripe-payments


【解决方案1】:

由于配置了 Route 属性为api/[controller],你不能直接访问 StripeWebHook 控制器。您需要配置条带以使用 websitename.com/api/StripeWebHook。

【讨论】:

    【解决方案2】:

    https://www.websitename.com/StripeWebHook/IndexStripeWebHookController 中调用名为 IndexGET 操作,同时使用 [HttpPost] 属性修饰 Index 操作。

    尝试删除上述代码中的[Route("api/[controller]")][HttpPost] 属性并再次测试。

    public class StripeWebHook : Controller
    {
    
        //[HttpPost]
        public async Task<IActionResult> Index()
        {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2015-04-12
      • 2012-06-16
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      相关资源
      最近更新 更多