api跨域

1.找方法名称是get开头的
2.找get请求类型的

自定义webapi的路由规则,控制到action

跨域设置:(服务端)
webconfig文件中,system.webServer节点下添加


<!--跨域请求:三个配置信息-->
<httpProtocol>
<customHeaders>
<!--响应类型 (值为逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法)-->
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
<!--响应头设置(Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain)-->
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<!--如果设置 Access-Control-Allow-Origin:*,则允许所有域名的脚本访问该资源-->
<add name="Access-Control-Allow-Origin" value="*" />
<!--<add name="Access-Control-Allow-Origin" value="http://domain1.com, http://domain2.com" /> 设置允许跨域访问的网址-->
</customHeaders>
</httpProtocol>

Global.asax 文件中配置跨域

/// <summary>
/// 跨域设置
/// </summary>
protected void Application_BeginRequest()
{
//OPTIONS请求方法的主要作用:
//1、获取服务器支持的HTTP请求方法;也是黑客经常使用的方法。
//2、用来检查服务器的性能。如:AJAX进行跨域请求时的预检,需要向另外一个域名的资源发送一个HTTP OPTIONS请求头,用以判断实际发送的请求是否安全。
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
//表示对输出的内容进行缓冲,执行page.Response.Flush()时,会等所有内容缓冲完毕,将内容发送到客户端。
//这样就不会出错,造成页面卡死状态,让用户无限制的等下去
Response.Flush();
}
}



请求不成功的原因:
1.路由不正确
2.请求的类型不匹配(get,post,put,delete)
3.参数个数和类型不匹配


<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)v11.0;AttachDbFilename=|DataDirectory|aspnet-BaweiExam.UI-20090101071652.mdf;Initial Catalog=aspnet-BaweiExam.UI-20090101071652;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>


<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>

WEB服务请求不成功
<system.web>

<webServices>
<protocols>
<add name="HttpPost,HttpGet" />
</protocols>
</webServices>
</system.web>





原文地址:https://www.cnblogs.com/qiao5799/p/13163066.html