mvc使用axios访问webapi
解决跨域问题
1.webapi安装cors
2.WebApiConfig下添加
public static void Register(HttpConfiguration config) { config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "MyApi", routeTemplate: "Myapi/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); }
3.mvc下安装axios
添加
<script src="~/Scripts/axios.min.js"></script>
代码:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
<script src="~/Scripts/vue.min.js"></script>
<link rel="stylesheet" href="~/Content/ElementUI/element-ui.css" />
<script src="~/Scripts/ElementUI/element-ui.js"></script>
<script src="~/Scripts/axios.min.js"></script>
</head>
<body>
<div id="app">
<el-button type="primary" v-on:click="getvalue(1234567)">主要按钮</el-button>
</div>
<script>
var myvue = new Vue(
{
el: "#app",
data: {
msg: "***",
msg2: null
},
methods:
{
getvalue: function (res)
{
axios.get('http://localhost:8081/Myapi/MyTest/getValue', {
params: {
id: res
}
})
.then(ret => {
alert(ret.data);
})
}
}
})
</script>
</body>
</html>