定义跨域handle

    public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin"; const string AccessControlRequestMethod = "Access-Control-Request-Method"; const string AccessControlRequestHeaders = "Access-Control-Request-Headers"; const string AccessControlAllowOrigin = "Access-Control-Allow-Origin"; const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin); bool isPreflightRequest = request.Method == HttpMethod.Options; if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew<HttpResponseMessage>(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault(); if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
} string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders)); if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
} return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}

在Global.asax注册handler

        protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}

webapi写法

        public string Get(int id)
{
var callback = HttpContext.Current.Request["callback"];
var u = new User { Name = "AA", Age = id };
var result = new JavaScriptSerializer().Serialize(u);
if (string.IsNullOrWhiteSpace(callback))
return result;
return string.Format("{0}({1})", callback, result);
}

前台写法

                $.ajax({
type: "get",
url: "http://localhost:21931/api/myapi/12311111",
contentType: "application/json;",
success: function (msg) {
jalert(JSON.stringify(msg));
},
error: function (a, b, c) {
jalert("error");
}
});

webapi之jsonp调用的更多相关文章

  1. MVC及WebAPI添加Jsonp支持

    Windows Live Writer 有点问题,着色代码看起来不清晰,所以贴的图片,完整代码在最后. 1:MVC实现 大致思路就是实现一个JsonpResult,在ExecuteResult内实现支 ...

  2. jsonp 调用天气API

    由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socket通讯 ...

  3. 使Asp.net WebApi支持JSONP和Cors跨域访问

    1.服务端处理 同源策略(Same Origin Policy)的存在导致了“源”自A的脚本只能操作“同源”页面的DOM,“跨源”操作来源于B的页面将会被拒绝.同源策略以及跨域资源共享在大部分情况下针 ...

  4. spring mvc jsonp调用示例

    服务端代码:主要是返回的时候,返回值要用callback包装一下 /** * JSONP调用 * * @param request * @return */ @RequestMapping(" ...

  5. jsonp调用webapi和mvc

    webapi代码如下: public string Get(int id) { var callback = HttpContext.Current.Request["callback&qu ...

  6. JS-JQuery(JSONP)调用WebService跨域若干技术点

    1.JSONP:JSON With Padding,让网页从别的网域获取信息,也就是跨域获取信息,可以当做是一种“工具”,大多数架构Jquery.EXTjs等都支持. 由于同源策略,一般来说位于 se ...

  7. Asp.net WebApi Put模式调用,“HTTP 错误 405.0 - Method Not Allowed”解决方法

    IIS10.0在部署了WebAPI之后,默认是不支持Put模式调用的.需要按照下面方法启用. 步骤一:在IIS管理界面要支持Put模式的IIS站点,选择 "功能视图". 步骤二:选 ...

  8. 【天坑】ASP.net WebAPI跨域调用问题

    最近在做一个项目,前端是VUE,后端是WebAPI,业务也就是一些实体的增删改查.在项目开始的时候我就预计到有跨域的问题,所以也找了一下资料,在Web.Config里面加上了配置信息: <htt ...

  9. WebAPI请求——js调用

    继续接着上文 ASP.NET MVC学习系列(一)-WebAPI初探 来看看对于一般前台页面发起的get和post请求,我们在Web API中要如何来处理. 这里我使用jQuery 来发起异步请求实现 ...

随机推荐

  1. 关于Windows Azure的常见问题-执行与维护FAQ

    执行与维护 使用虚拟机运行业务应用有什么需要注意的地方? Windows Azure 会周期性地更新主机环境,以确保平台上运行的所有应用程序和虚拟机始终处于安全的环境.此更新过程可能会导致您的虚拟机重 ...

  2. ionic如何uglify和minify你的js,css,image,png....

    Install:   1.ionic start myapp blank      2.cd myapp     3.npm install cordova-uglify or npm install ...

  3. ndk-gdb of NDK r9d modified to *always* debug the ":remote"-process of your app

    https://gist.github.com/TomTasche/9690186 ndk-gdb of NDK r9d modified to *always* debug the ":r ...

  4. Lua包管理工具Luarocks详解 - 15134559390的个人空间 - 开源中国社区

    Lua包管理工具Luarocks详解 - 15134559390的个人空间 - 开源中国社区 Lua包管理工具Luarocks详解

  5. Learning JavaScript Design Patterns The Observer Pattern

    The Observer Pattern The Observer is a design pattern where an object (known as a subject) maintains ...

  6. IOS - view之间切换

    //进入下一页 - (IBAction)Go:(id)sender { TwoViewController *twoVC = [[TwoViewController alloc] init];//这里 ...

  7. SGU107——987654321 problem

    For given number N you must output amount of N-digit numbers, such, that last digits of their square ...

  8. 调用webservice,解析返回数据为xml格式的字符串,进行数据绑定

    DataSet ds = new DataSet(); byte[] byteArray = System.Text.Encoding.Unicode.GetBytes("<?xml ...

  9. 《编程导论(Java)&#183;2.1.3改写(override)》

    <编程导论(Java)·2.1.3改写(override)>,收集override内容. 方法改写(method overriding)是指对于父类定义的一个实例方法,同意子类提供自己的实 ...

  10. (二)Java对象与内存控制

    一.java的类变量和实例变量: java中的变量可分成两种:成员变量和局部变量. 1.局部变量包括以下几类: 方法内的局部变量:作用域为方法体. 代码块内的局部变量:作用域为代码块 形参:方法内的形 ...