Ajax cross-Domain call solution for ASP. NET MVC or WEBAPI services

Source: Internet
Author: User

Problem description

When cross domain calls the services written by ASP. NET MVC or the ASP. NET Web API, an inaccessible condition occurs.

How to Reproduce

    1. Create one of the simplest ASP. NET Web API projects with a template and debug to confirm that it works
    1. public class Usercontroller:apicontroller
    2. {
    3. Public Usermodel GetInfo ()
    4. {
    5. Usermodel um = new Usermodel ();
    6. Um. Uid = 5;
    7. Um. UserName = "ADDDDN";
    8. Um. Age = 117;
    9. Return um;
    10. }

12.}

13.public class Usermodel

    1. {
    2. public int Uid {get; set;} Number
    3. public string UserName {get; set;} Name
    4. public int Age {get; set;} Age
    5. }
    1. Create another project that contains only an HTML page, initiating an AJAX call

20.<script type= "Text/javascript" >

    1. Window.onload = function Get () {
    2. $.ajax ({
    3. Type: ' GET ',
    4. URL: ' Http://192.168.10.106:8088/api/user/getInfo ',

DataType: ' JSON ',

    1. Success:function (data, textstatus) {
    2. Alert (data. Uid + "|" + data. UserName + "|" + data. Age);
    3. },
    4. Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
    5. }
    6. });
    7. }
    1. Open this page in the browser, we will find the following error (405:method not allowed)

"Remarks" in the same case, also occurs in ASP. At some point, MVC can also be used to develop services directly, with advantages and disadvantages compared to WEBAPI. The following is an example of a service developed using MVC

    1. Public ActionResult Index ()
      {
      Usermodel um = new Usermodel ();

Um. Uid = 5;

    1. Um. UserName = "ADDDDN";
    2. Um. Age = 117;


Return Json (Um, jsonrequestbehavior.allowget);
}

Cause analysis

A cross-domain problem occurs only when JavaScript initiates an Ajax call, or when Silverlight initiates a service invocation, because the browser is given a lower permission for both requests, usually allowing only the resources in the domain to be called. Unless the target server explicitly tells it to allow cross-domain calls.

Therefore, the cross-domain problem is caused by the behavior of the browser, but the solution is on the server side. Because it is not possible to require all clients to reduce security.

Solution Solutions 1

For the two project types of ASP. NET MVC and ASP, I did some research to make sure the following scenario is feasible.

For ASP. NET MVC, just add the following red content to the Web. config

<system.webServer>

<customHeaders>

<addname= "Access-control-allow-origin" value= "*"/>

<addname= "Access-control-allow-headers" value= "Content-type"/>

<addname= "Access-control-allow-methods" value= "GET, POST, Put,delete, OPTIONS"/>

</customHeaders>

</system.webServer>

In addition to the above settings, for the ASP. NET Web API, you need to add a special design that adds an options method to each Apicontroller, but does not need to return anything.

public string Options ()

{

return null; HTTP response with empty body

}

"Remarks" This function can also do some research, design the form of filter may be better.

Solution 2 (for MVC)

The following index is the method that needs to be called

Public ActionResult Index ()
{

String t = Requesturl ("Http://192.168.1.3/api/user/getInfo");
Jsondata js = jsonmapper.toobject (t);
String name = (string) js["UserName"];
return Content (name);
}

public static string Requesturl (string url)
{
string strurl = URL;
System.Net.HttpWebRequest request;
Request = (System.Net.HttpWebRequest) webrequest.create (strURL);
Request. Method = "GET";

System.Net.HttpWebResponse response;
Response = (System.Net.HttpWebResponse) request. GetResponse ();
System.IO.Stream s;
s = Response. GetResponseStream ();
String strdate = "";
string strvalue = "";
StreamReader Reader = new StreamReader (s, Encoding.UTF8);
while ((strdate = Reader.readline ()) = null)
{
strvalue + = strdate + "\ r \ n";
}
return strvalue;
}

Ajax cross-Domain call solution for ASP. NET MVC or WEBAPI services

Related Article

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.