如何用JavaScript向启用Windows身份验证的ASP.NET Web API发送带Payload的POST请求
可以通过JavaScript成功调用该接口,以下是解决访问被拒问题的具体配置步骤
前端配置(React/JavaScript)
核心是让请求携带Windows身份验证凭据,不同请求库的配置方式如下:
使用fetch
fetch('https://your-api-domain/api/v1/testuser/Generic/UpdateData', { method: 'POST', credentials: 'include', // 关键:携带身份凭据 headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ // 填入你的GenericPayload结构数据 key1: 'value1', key2: 123 }) }) .then(res => { if (!res.ok) throw new Error('请求失败'); return res.json(); }) .catch(err => console.error(err));
使用axios
axios.post('https://your-api-domain/api/v1/testuser/Generic/UpdateData', { // GenericPayload数据 key1: 'value1', key2: 123 }, { withCredentials: true, // 关键:携带身份凭据 headers: { 'Content-Type': 'application/json' } } ) .then(res => console.log(res.data)) .catch(err => console.error(err));
后端配置(ASP.NET Web API)
需要同时配置CORS允许凭据传递,以及确保Windows身份验证正常生效:
1. 启用并配置CORS
在WebApiConfig.cs中添加CORS配置,注意不能用*作为允许的源(浏览器不允许通配源同时支持凭据),要指定具体的前端域名:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 配置CORS,允许指定前端域名、所有请求方法和头,支持凭据 var corsSettings = new EnableCorsAttribute("https://your-frontend-domain", "*", "*") { SupportsCredentials = true }; config.EnableCors(corsSettings); // 启用属性路由 config.MapHttpAttributeRoutes(); } }
2. 确保控制器授权
给UpdateData方法添加[Authorize]属性,确保只有通过Windows身份验证的用户能访问:
public class GenericController : ApiController { [Route("api/{version}/{user}/Generic/UpdateData")] [HttpPost] [Authorize] // 添加授权验证 public HttpResponseMessage UpdateData([FromBody] GenericPayload parameter) { // 你的业务逻辑 return Request.CreateResponse(HttpStatusCode.OK); } }
3. IIS站点配置
- 打开IIS管理器,找到你的API站点,进入身份验证设置
- 启用Windows身份验证,禁用匿名身份验证
关键注意事项
- 前后端必须是同源,或者后端CORS配置的源与前端域名完全匹配(包括协议、域名、端口)
- 浏览器会对跨域POST请求先发OPTIONS预检请求,后端CORS配置要确保允许OPTIONS方法
- 本地开发时,若使用localhost域名,浏览器默认允许凭据传递,无需额外设置
内容的提问来源于stack exchange,提问作者Romil Kumar Jain
相关产品推荐
相关产品推荐

