You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Aurelia调用ASP.NET Core Web API跨域错误:预检请求未通过检查

Fixing CORS and Object Mapping Issues for ASP.NET Core 2.0 Web API + Aurelia

Hey there! Let's tackle each of your questions step by step to get your setup working smoothly.


1. Resolving the "No 'Access-Control-Allow-Origin' header" and "POST not allowed" CORS Errors

Your current CORS configuration only whitelists the origin (http://localhost:9000) but doesn't explicitly allow the HTTP methods (like POST) or request headers (like Content-Type) that your Aurelia app uses. Browsers send a preflight OPTIONS request before the actual POST to verify the server's CORS policy, and your setup isn't handling that properly.

Here's how to update your Startup.cs to fix this:

Updated 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.Extensions.DependencyInjection;

namespace Syslog.Web.GradeSheet.Backend {
    public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddMvc();
            // Define a reusable named CORS policy
            services.AddCors(options => {
                options.AddPolicy("AureliaCorsPolicy", policy => {
                    policy.WithOrigins("http://localhost:9000")
                          .AllowAnyMethod() // Permit all HTTP methods (POST, OPTIONS, etc.)
                          .AllowAnyHeader(); // Allow request headers like Content-Type
                });
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }

            // Apply the CORS policy (must run BEFORE UseMvc)
            app.UseCors("AureliaCorsPolicy");

            app.UseMvc();

            app.Run(async (context) => {
                await context.Response.WriteAsync("Welcome To GradeSheet Web Service! MVC has not found any Route that has been matched yet.");
            });
        }
    }
}

Key fixes:

  • Added a named policy that explicitly allows required methods and headers (you can restrict to POST/OPTIONS and Content-Type if you want stricter control)
  • Ensured UseCors runs before UseMvc—this order is critical to handle preflight requests correctly

2. PostMan Works But Aurelia Fails: Is It a Client Issue?

Nope, this isn't a client problem! PostMan skips browser-enforced CORS rules—it doesn't send the preflight OPTIONS request and directly sends the POST. Browsers, however, require this preflight check to validate cross-origin access. Once you fix your server's CORS config (as above), Aurelia will work just like PostMan.


3. Can the Web Service Automatically Map POSTed Objects from Aurelia?

Absolutely—as long as two conditions are met:

  1. Your server-side SampleData class has matching property names (spelling must match; casing is handled automatically by JSON serializers)
  2. Your Aurelia app sends requests with Content-Type: application/json (which you already configured in your HttpClient setup)

Add This Server-Side SampleData Class

You're missing this in your backend project—add it to make object mapping work:

namespace Syslog.Web.GradeSheet.Backend {
    public class SampleData {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

ASP.NET Core's default JSON serializer automatically maps camelCase properties from your Aurelia app (name, age) to PascalCase properties in your C# class (Name, Age)—no extra setup needed here.


4. Fixing "Request method POST not allowed in CORS policy"

This is directly caused by your incomplete CORS configuration. The fix is the same as in question 1: update your policy to explicitly allow the POST method (or use AllowAnyMethod() for development). Once you apply the updated Startup.cs code, this error will disappear because the policy now permits POST requests from your Aurelia origin.


Quick Verification Steps After Changes

  1. Restart your ASP.NET Core Web API
  2. Clear your browser's cache (to avoid stale CORS-related issues)
  3. Run your Aurelia app—you should see the success message in the console!

内容的提问来源于stack exchange,提问作者Jerald James Capao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:21:13