asp.net webapi 跨域问题解决 No 'Access-Control-Allow-Origin' header i

一、基础解决方案(基础配置)

通过Ajax调用web api路径时报错:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

C#自带的web api并不能支持跨域访问,如果需要,可以更改配置来实现。

1、更改Web.config文件,加上如下代码


      
        
        
        
      

2、然后需要配置Global.asax文件

插入如下代码:

       /// 
        /// 配置Ajax跨域访问
        /// 
        /// 
        /// 
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.HttpMethod.ToUpper() == "OPTIONS")
            {
                Response.StatusCode = 200;
                Response.End();
            }
        }

配置这两个文件之后,web api就可以跨域访问了。

二、跨域产生异常的解决方案

1、webapi处理OPTIONS请求 报错1信息

Access to XMLHttpRequest at 'https://localhost:4445/api/v/getmsg' from origin 'https://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

解决方案:把value值改成特定的域名

   
  
    
      "Access-Control-Allow-Origin" value="https://localhost:8083" />
  
    

2、Access to XMLHttpRequest at 'https://localhost:4445/api/v/getmsg' from origin 'https://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

配置行继续添加

<"Access-Control-Allow-Credentials" value="true" />

3、It does not have HTTP ok status Ajax请求一般会做options状态监测,需要返回200

Access to XMLHttpRequest at 'https://localhost:4445/api/v/getmsg' from origin 'https://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

        Global.asax 中添加
        /// 
        /// 配置Ajax跨域访问
        /// 
        /// 
        /// 
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.HttpMethod.ToUpper() == "OPTIONS")
            {
                Response.StatusCode = 200;
                Response.End();
            }
       }

 

 

 

 

你可能感兴趣的:(WEBAPI,iis,webapi)