在Asp.net MVC中在同源中可以随便访问,但是一般多数都需要进行跨域访问,因此就需要对webapi进行一些配置。
1、需要在nuget中下载一个包:Microsoft.Net.WebApi.Cors
2、添加代码实现
在App_Start文件夹下面的WebApiConfig.cs类里面的Register方法下面增加允许跨域的实现
详细代码如下:
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//获取配置文件中的跨域配置
var allowedOrigin = ConfigurationManager.AppSettings["allowedOrigin"];
//跨域配置
EnableCorsAttribute coreAttr = new EnableCorsAttribute(allowedOrigin, "*", "*")
{
SupportsCredentials = true
};
config.EnableCors(coreAttr);
}
3、在webconfig配置文件中添加配置
实现代码如下:
<appSettings>
<add key="allowedOrigin" value="*" />
</appSettings>
以上便是实现在Asp.Net中WebApi实现跨域的操作,希望能帮助到你 谢谢!