Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of javascript cross-domain request encountered by ASP.NET in developing web applications

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to solve the problem of javascript cross-domain requests encountered in the development of web applications by ASP.NET". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Solution

Cross-domain post requests are not encouraged.

Cross-domain Scheme jsonp of ajax in 0.jquery

.ashx code

Using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace KB.DSN.Web.API.Tokens {/ Summary description for Get / 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 page

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 only supports GET requests, not POST requests. Even if you write POST, it will automatically convert to GET requests and put your data in querystring.

1. Modify the web.config file

The whole application supports cross-domain requests.

Web.config

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" cannot be set in this way, otherwise it will prompt "Request header field Content-Type is not allowed by Access-Control-Allow-Headers." Just remove the contentType setting from ajax! If you want to set contentType, you need to change the web.config file to

Web.config does not support the system.webServer configuration section in II6, so you need to set httprequestheader in IIS. Add the custom headers in the web.config file to the settings of IIS.

FindContact.ashx

/ / /

/ Summary description for FindContact

/ / /

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 (input)

Var list = new List ()

List.Add (o)

List.Add (o)

Context.Response.Write (Newtonsoft.Json.JsonConvert .SerializeObject (list))

}

Public bool IsReusable

{

Get

{

Return false

}

}

}

two。 Set HttpHeader in the request

For a single request.

FindContact.ashx/// Summary description for FindContact / 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 (input); var list = new List (); list.Add (o); list.Add (o); # region supports cross-domain request 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

3. Use proxy

Suppose you have two web applications: one that puts html pages to provide an interface to the user, and one that provides services that use .ASHX to process requests.

The interface where you use ajax to request ashx applications in html applications is ajax cross-domain requests.

You can write some background code in the html application and submit the data to the ashx application in the code.

Then the collected data from the page of your html application is sent to the background code of the html application, and the background code sends the data to the ashx application. This is not an ajax cross-domain request.

The background code in the html application is called a "proxy", which acts as a proxy for requests from the html application to the ashx application.

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 ();}});}

This is the end of the content of "how to solve the problem of javascript cross-domain requests encountered in ASP.NET development of web applications". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report