由于CORS,Angular请求无法访问API控制

时间:2019-09-04 11:53:55

标签: c# angular cors asp.net-web-api2

我有一个端点,可以简单地上传个人资料图片。尽管我启用了CORS,但前端团队不断告诉我,由于出现以下错误,他们无法到达该端点:

  

zone.js:2990从原点'https://gogobioimages.testortami.com/api/Image/PostAccountPicture'对'http://localhost:4200'处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:未通过具有HTTP正常状态。

它们在Angular上开发。另一方面,移动团队(在Xamarin上开发)在达到该终点方面没有任何问题。以下是我对API控制器的细分。

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class BaseController : ApiController
{
    //common methods used on every controller written here
}

而且,这是包含图像上传方法的终点:

public class ImageController : BaseController
{
    [IdentityBasicAuthentication]
    [Authorize]
    public HttpResponseMessage PostAccountPicture()
    {
        //some code here
    }
}

首先,将这些[Authorize][IdentityBasicAuthentication]标头放在ImageController的顶部,但是我读到这种情况最终可能会混合请求管道,因此我将它们移到了行动的顶部(虽然并不能解决问题)。

我的web.config中也有以下customHeader行:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Credentials" value="true"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
  </customHeaders>
</httpProtocol>

而且,我的处理程序描述如下:

<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <!--<remove name="OPTIONSVerbHandler" />-->
  <remove name="TRACEVerbHandler" />
  <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

一开始,我没有name="OPTIONSVerbHandler"。将其添加到web.config后,移动请求开始出现500 Internal Server Error。

下面是我的Global.asax,我已根据其他建议对其进行了编辑(开头没有包括Application_BeginRequest

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.Flush();
        }
    }
}

最后,我的WebApiConfig类如下:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

我还要求我的前端伴侣与我分享她的ajax请求。就像这样:

  $("form").submit(function(evt){evt.preventDefault(); var formData = new FormData($(this)[0]); $.ajax({
url: 'https://<our subdomain name is here>/api/Image/PostAccountPicture',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
headers: {'Authorization':'Basic ' + localStorage.getItem('currentUser')} ,
success: function (response) {
  alert(response);
}});return false;});

我在以前的项目中也启用了CORS,足以在控制器类上设置[EnableCors("*","*","*")]并在config.EnableCors()上进行WebApiConfig.cs,而无需进行上述所有其他调整。在web.config文件中。

现在,我不知道是什么使前端保持到达终点。

提前谢谢!

2 个答案:

答案 0 :(得分:0)

您能否尝试在有角度的一端发送跨域/跨域:true 像下面这样
标题:{         '授权':'基本'+ localStorage.getItem('currentUser'),         'Access-Control-Allow-Origin':'*',                 'Access-Control-Allow-Headers':'来源,X-请求使用,内容类型,接受'      }

答案 1 :(得分:0)

在使用angular进行开发并在浏览器和后端之间使用本地服务器时,我遇到了同样的问题(以便在代码更改时即时更新gui)。我们只需添加Allow CORS Plugin就解决了该问题 当处理此消息的服务器与发送api调用的服务器不同时,Chrome(我想其他浏览器)会感到厌恶。

这当然在生产中是没有问题的,因为浏览器可以到达预期的服务器,而不是中间服务器的人。