|
|

以前,遇到过控制器的跨域请求,然后,知道在web.config里面加上几句话就可以了。。。。
这次在web.config加上如下:
- <system.webServer>
- <httpProtocol>
- <customHeaders>
- <add name="Access-Control-Allow-Origin" value="*" />
- <add name="Access-Control-Allow-Headers" value="*" />
- <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
- <add name="Access-Control-Request-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
- <!--允许请求的http 动作-->
- </customHeaders>
- </httpProtocol>
复制代码
发现,还是不允许跨域请求,why?????是不是webapi和控制器不一样啊,
可能是真的不一样,解决方法如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http.Filters;
- namespace SUI.Controllers
- {
- public class CrossSiteAttribute : ActionFilterAttribute
- {
- private const string Origin = "Origin";
- private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
- private const string originHeaderdefault = "*";
- public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
- {
- actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, originHeaderdefault);
- }
- }
- }
复制代码
webapi如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace SUI.Controllers
- {
- public class OpenController : ApiController
- {
- [CrossSiteAttribute]
- public Test Get(string keyword)
- {
- return new Test
- {
- keyword = keyword,
- age = 20
- };
- }
- }
- public class Test {
- public string keyword { get; set; }
- public int age { get; set; }
- }
- }
复制代码
成功解决了!
|
上一篇:C# 中2,10,16进制及其ASCII码之间转化下一篇:c# post数据的时候压缩数据
|