您的位置:首页 > 编程语言 > ASP

asp.net mvc web api 可跨域方法

2015-10-09 15:43 274 查看
1.直接修改 web.config ,不过这是针对所有 Action。

<location path="Sample.txt">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>

方法 2.

加入一个类别,内容为以下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System;
using System.Web.Http.Filters;

namespace Workflow.Filters
{
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

base.OnActionExecuted(actionExecutedContext);
}
}
}

最后你在 Controller 或者是 Action 上面加上属性,即可允许跨网域传输数据:

[AllowCrossSiteJson]
public class InstancesController : ApiController
{
// ......

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: