Advertisement
Intermediate ASP.NET Core, CORS (Cross-Origin Resource Sharing)

How does the WithMethods() CORS policy builder method restrict cross-origin requests, and why is it preferable to AllowAnyMethod() for sensitive endpoints?

Short answer

WithMethods() explicitly whitelists which HTTP methods (GET, POST, PUT, DELETE) are permitted for cross-origin requests under a policy, following the principle of least privilege -- a read-only public API can restrict cross-origin access to GET only, preventing any cross-origin…

Save ASP.NET Core mock interview
Advertisement
AModel answer
WithMethods() explicitly whitelists which HTTP methods (GET, POST, PUT, DELETE) are permitted for cross-origin requests under a policy, following the principle of least privilege -- a read-only public API can restrict cross-origin access to GET only, preventing any cross-origin attempt at POST/PUT/DELETE even if other parts of the CORS policy were accidentally misconfigured too permissively.
options.AddPolicy("ReadOnlyPublic", policy => {
    policy.WithOrigins("https://partner-site.com")
          .WithMethods("GET")  // only GET allowed cross-origin, not POST/PUT/DELETE
          .AllowAnyHeader();
});
Real-world example
A public read-only reporting API restricts its CORS policy to WithMethods("GET") specifically so that even if a partner site's origin configuration were somehow compromised, cross-origin write operations remain impossible regardless of any other misconfiguration.
Likely follow-ups
  • How does this interact with preflight requests for methods not in the allowed list?
  • Should WithMethods generally be preferred over AllowAnyMethod in production APIs?
Related topics