What does the WithMethods() CORS policy builder method control, and why restrict it instead of using AllowAnyMethod()?
Short answer
WithMethods() explicitly whitelists which HTTP methods (GET, POST, PUT, DELETE, etc.) are permitted for cross-origin requests under a policy, letting you follow the principle of least privilege by only allowing the specific methods an origin actually needs -- e.g., a read-only…
Advertisement
AModel answer
WithMethods() explicitly whitelists which HTTP methods (GET, POST, PUT, DELETE, etc.) are permitted for cross-origin requests under a policy, letting you follow the principle of least privilege by only allowing the specific methods an origin actually needs -- e.g., 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 misconfigured.
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 is 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?
Related topics