Implementation of cross-domain MVC service calling and Cookie Verification Based on C # backend

Source: Internet
Author: User

Background
With the prevalence of rich client frameworks and numerous excellent front-end js frameworks, we may encounter cross-origin problems in many cases, while JavaScript ajax requests do not allow direct cross-origin access, of course, you may say that JSONP can be used, but due to code cleanliness, you do not want to add callback in the front end and backend, and in many cases you cannot control, so too many cases need to be considered.

Therefore, I directly bypassed each front-end application and provided a general backend Service proxy. This service solves cross-origin problems and the automatic proxy helps the front-end obtain cross-Origin data.

How to calculate cross-Origin
Although it is an old problem, we still need to note the following two points: Data Access is cross-origin for the same IP address and different ports, but Cookie Access is acceptable (This makes it hard for me to understand)

Solution, source code

Copy codeThe Code is as follows: CookieContainer cookieContainer = new CookieContainer ();

[HttpPost]
Public string CommonPost (string url)
{
Log. Info (CookieHelper. GetCookie ("ITDC_UserName") + "access method CommonPost Url =" + url );
Uri address = new Uri (System. Configuration. ConfigurationManager. receivettings ["RESTfulAPI"]. ToString () + url );
HttpWebRequest request = WebRequest. Create (address) as HttpWebRequest;
Request. Method = "POST ";
Request. ContentType = "application/x-www-form-urlencoded ";
// Remote service, which requires cookie Verification
CookieContainer. Add (address, GetCookie ("ITDC_UserName "));
CookieContainer. Add (address, GetCookie ("ITDC_UserRole "));
Request. CookieContainer = cookieContainer;
StringBuilder data = new StringBuilder ();
For (int I = 0; I <Request. QueryString. Count; I ++)
{
If (Request. QueryString. Keys [I]. ToString () = "url") continue;
Data. Append ("&" + Request. QueryString. Keys [I]. ToString () + "=" + Request. QueryString [I]. ToString ());
}
// Create a byte array of the data we want to send
Byte [] byteData = UTF8Encoding. UTF8.GetBytes (data. ToString (). TrimStart ('&'));
// Set the content length in the request headers
Request. ContentLength = byteData. Length;
// Write data
Using (Stream postStream = request. GetRequestStream ())
{
PostStream. Write (byteData, 0, byteData. Length );
}
String result = "";
Using (HttpWebResponse response = request. GetResponse () as HttpWebResponse)
{
StreamReader reader = new StreamReader (response. GetResponseStream ());
Result = reader. ReadToEnd ();
}
Log. Info (CookieHelper. GetCookie ("ITDC_UserName") + "completed CommonPost Url =" + url );
Return (result );
}

Frontend call
Copy codeThe Code is as follows: Ext. Ajax. request ({url: APIUrl + '/Nebula/CommonPost? Url =/Nebula/PostComment/& KlId = 1 & Msg = OK & Author = admin & Title = article Title ',
Method: "POST ",
Success: function (response ){
Ext. Viewport. unmask ();
Var obj = Ext. decode (response. responseText );
Ext. Msg. alert ("prompt", obj. Msg, Ext. emptyFn );
},
Failure: function (response ){
Ext. Viewport. unmask ();
Ext. Msg. alert ("prompt", "operation failed. Please check the network! ", Ext. emptyFn );
}
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.