Skip to main content
 首页 » 编程设计

c#之从 WebAPI Controller 重定向到子域之需要 CORS

2024年02月01日27JustinYoung

目前,我的 WebAPI Controller 执行此操作:

var newUrl = _adminService.Foo(bar); 
return Request.CreateResponse(HttpStatusCode.OK, newUrl); 

于是客户端接收到一个字符串,然后用javascript设置window.location。

这似乎是一种通过 WebAPI 重定向的 hacky 方式。我找到了这篇文章:

Redirect from asp.net web api post action

我已经实现了:

var newUrl = _adminService.Foo(bar); 
var response = Request.CreateResponse(HttpStatusCode.Moved); 
response.Headers.Location = new Uri(newUrl); 
return response; 

但现在我在 chrome 中收到以下错误(从本地主机导航到子域时):

XMLHttpRequest cannot load http://test.localhost:3806/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3806' is therefore not allowed access.   

我需要为此配置 CORS 吗?

请您参考如下方法:

Do I need to configure CORS for this?

是的,如果您的 javascript 托管在与 Web API 不同的域中,您确实需要。