【发布时间】:2017-04-21 16:17:38
【问题描述】:
我有一个在我们的 Intranet 中使用的 Web API 应用程序。我们还使用 Windows 身份验证来限制谁可以访问 Intranet 中的这些 Web API。
此外,我们还有一个 angularJS 应用程序。它使用 WEB API 应用程序。这些应用程序的领域是不同的。因此我们使用了 CORS。
为了启用 CORS,我们使用了 Microsoft CORS Nuget 包。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var cors = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
config.EnableCors(cors);
}
}
我有两个 WEB API(GET 和 POST)。加载我的 UI 时,会调用 GET API。当用户单击保存按钮时,会调用 POST API。
[RoutePrefix("api/call")]
[Authorize]
public class CallController : TecApiController
{
[HttpGet]
[Route("GetInfo")]
public IHttpActionResult GetCallInfo(int Id)
{
//return Model
}
[HttpPost]
[Route("saveInfo")]
public IHttpActionResult SetUncompleteCallToDismissed([FromBody] Model model)
{
// Save Model
}
}
我调用 API 的 AngularJS 服务如下
$http.get(apiEndPoint + 'GetInfo/' + Id, { withCredentials: true })
.then(function (response) { return response.data; }, handleError);
$http.post(apiEndPoint + 'saveInfo/', model, { withCredentials: true })
.then(function (response) { return response.data; }, handleError);
我的问题是 GET 方法运行良好。但是当我点击帖子时,我的浏览器控制台出现以下错误:
XMLHttpRequest 无法加载 http://localhost:35059/api/call/saveInfo。回应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:3000” 使用权。响应的 HTTP 状态代码为 401。
这里发生的最复杂的事情是当我运行 Fiddler 来调试请求时,一切都变得很好。
请告诉我如何修复它。
【问题讨论】:
标签: c# angularjs asp.net-web-api cors