温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么解决ASP.NET开发web应用遇到的javascript跨域请求问题

发布时间:2021-11-20 16:05:33 来源:亿速云 阅读:206 作者:iii 栏目:编程语言

本篇内容介绍了“怎么解决ASP.NET开发web应用遇到的javascript跨域请求问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

解决方案

不提倡跨域的post请求。

0.jquery中ajax的跨域方案jsonp

.ashx代码

 

using System; using System.Collections.Generic; using System.Linq; using System.Web;  namespace KB.DSN.Web.API.Tokens {     /// <summary>     /// Summary description for Get     /// </summary>     public class Get : IHttpHandler     {           public void Proce***equest(HttpContext context)         {             setresponsecontext(context);             var token = KB.DSN.BusinessAccess.UniqueCommunicationCode.GenerateUniqueCommunicationCode();              var outputobject = new             {                 Head = new Models.KBJsonHeadResponse(),                 Body = new { Token = token }             };              var outputjsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(outputobject);                           context.Response.Write(context.Request.QueryString["callback"]+"("+outputjsonstring+")");          }          private void setresponsecontext(HttpContext context)         {                         context.Response.ContentEncoding = System.Text.Encoding.UTF8;             context.Response.ContentType = "application/json";         }          public bool IsReusable         {             get             {                 return false;             }         }     } }




html页面

 

function getToken_jsonp(){         $.ajax({        url: "http://192.168.0.111/api/tokens/get.ashx",           type: "get",      dataType: "jsonp",     jsonp: "callback",     async: false,                contentType: "application/json",           success: function(data){       //alert("getToken success");             $("#token").text($.toJSON(data));             //console.log(data);                  },     error:function(){         alert("getToken fail");     }         });        }

jsonp只支持GET请求,不支持POST请求,就算你写了POST,它会自动转换为GET请求,把你的data放在querystring中。

1.修改web.config文件

整个应用都支持跨域的请求。

web.config

<system.webServer>    <httpProtocol>     <customHeaders>       <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>       <add name="Access-Control-Allow-Headers" value="x-requested-with"/>       <add name="Access-Control-Allow-Origin" value="*" />     </customHeaders>   </httpProtocol> </system.webServer>

html page

function addContact() {            var contact = new Object();            contact.FirstName = $("#firstName").attr("value");            contact.LastName = $("#lastName").attr("value");            contact.PhoneNo = $("#phoneNo").attr("value");            contact.EmailAddress = $("#emailAddress").attr("value");            $.ajax({                url: "http://localhost:10401/api/contacts/AddContact.ashx",                type: "POST",                 dataType: "json",                data: $.toJSON(contact),                  success: function () { loadAllContacts(); }            });        }
 这种方式不能设置contentType: "application/json",否则会提示"Request header field Content-Type is not allowed by Access-Control-Allow-Headers."去掉ajax中的contentType设置就可以了!  想要设置contentType也可以,需要将web.config文件中的<add name="Access-Control-Allow-Headers" value="x-requested-with"/> 修改为<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>

 在II6中web.config不支持system.webServer配置节,所以需要在IIS中设置httprequestheader。将web.config文件中的自定义头加入IIS的设置中。

怎么解决ASP.NET开发web应用遇到的javascript跨域请求问题

FindContact.ashx

  1. /// <summary> 

  2.    /// Summary description for FindContact 

  3.    /// </summary> 

  4.    public class FindContact : IHttpHandler 

  5.    { 

  6.  

  7.        public void Proce***equest(HttpContext context) 

  8.        { 

  9.            context.Response.ContentEncoding = Encoding.UTF8; 

  10.            context.Response.ContentType = "application/json"

  11.  

  12.            var stream = context.Request.InputStream; 

  13.            var reader = new StreamReader(stream); 

  14.            var input=reader.ReadToEnd(); 

  15.  

  16.            var o = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.Contact>(input); 

  17.            var list = new List<Models.Contact>(); 

  18.            list.Add(o); 

  19.            list.Add(o); 

  20.            context.Response.Write(Newtonsoft.Json.JsonConvert .SerializeObject ( list )); 

  21.        } 

  22.  

  23.        public bool IsReusable 

  24.        { 

  25.            get 

  26.            { 

  27.                return false

  28.            } 

  29.        } 

  30.    } 

 

2.在请求中设置HttpHeader

针对单个请求。

FindContact.ashx

/// <summary>    /// Summary description for FindContact    /// </summary>    public class FindContact : IHttpHandler    {         public void Proce***equest(HttpContext context)        {            context.Response.ContentEncoding = Encoding.UTF8;            context.Response.ContentType = "application/json";             var stream = context.Request.InputStream;            var reader = new StreamReader(stream);            var input=reader.ReadToEnd();             var o = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.Contact>(input);            var list = new List<Models.Contact>();            list.Add(o);            list.Add(o);             #region 支持跨域请求            context.Response.ClearHeaders();            string origin = context.Request.Headers["Origin"];            context.Response.AppendHeader("Access-Control-Allow-Origin",                string.IsNullOrEmpty(origin) ? "*" : origin);            string requestHeaders = context.Request.Headers["Access-Control-Request-Headers"];            context.Response.AppendHeader("Access-Control-Allow-Headers",                string.IsNullOrEmpty(requestHeaders) ? "*" : requestHeaders);            context.Response.AppendHeader("Access-Control-Allow-Methods", "POST, OPTIONS");            #endregion             context.Response.Write(Newtonsoft.Json.JsonConvert .SerializeObject ( list ));        }         public bool IsReusable        {            get            {                return false;            }        }    }

html page

function addContact() {            var contact = new Object();            contact.FirstName = $("#firstName").attr("value");            contact.LastName = $("#lastName").attr("value");            contact.PhoneNo = $("#phoneNo").attr("value");            contact.EmailAddress = $("#emailAddress").attr("value");            $.ajax({                url: "http://localhost:10401/api/contacts/AddContact.ashx",                type: "POST",                 dataType: "json",                data: $.toJSON(contact),                  success: function () { loadAllContacts(); }            });        }

3.使用代理

假设你有两个web应用:一个应用放html页面,给用户提供界面;一个应用放服务,使用.ASHX处理请求。

你在html应用中使用ajax请求ashx应用的接口,就是ajax跨域请求。

你可以在html应用中写一些后台代码,在代码中向ashx应用提交数据。

然后你的html应用的页面中将收集到的数据发送到html应用的后台代码中,由后台代码发送数据到ashx应用,这就不是ajax跨域请求了。

在html应用中的后台代码就被叫做“代理”,代理html应用到ashx应用的请求。


“怎么解决ASP.NET开发web应用遇到的javascript跨域请求问题”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI