Add the following configuration under the System.webserver node in the Web.config file:
<system.web>
<authentication mode= "None"/>
<compilation debug= "true" targetframework= "4.5" />
Specify that sites allow Cross-domain access (base class)
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC; Namespace Webapplication1.app_start {public class Alloworiginattribute {public static void Onexcute (Cont Rollercontext context, string[] Allowsites} {var origin = context.
httpcontext.request.headers["Origin"]; Action action = () => {context.
HttpContext.Response.AppendHeader ("Access-control-allow-origin", Origin);
};
if (allowsites!= null && allowsites.any ()) {if (Allowsites.contains (Origin))
{action (); }}} public class Actionalloworiginattribute:actionfilterattribute {public
String[] Allowsites {get; set;} public override void OnActionExecuting (System.Web.Mvc.ActionExecutingContext filtercontext) {Allowori GiNattribute.onexcute (Filtercontext, allowsites); Base.
OnActionExecuting (Filtercontext); } public class Controlleralloworiginattribute:authorizeattribute {public string[] Allowsites {ge T Set } public override void Onauthorization (System.Web.Mvc.AuthorizationContext filtercontext) {Al
Loworiginattribute.onexcute (Filtercontext, allowsites); }
}
}
Specifies that controller allows cross-domain access
[Controlleralloworigin (allowsites = new string[] {"http://localhost:52559"})]
public class Citycontroller:controller
{}
Specifies that the action allows Cross-domain access
[HttpPost]
[Actionalloworigin (allowsites = new string[] {"http://localhost:52559"})]
Public ActionResult addcity (string userName, string password)
{
var a = UserName;
var b = password;
Return Json (new
{
Code =,
msg = "123",
data = ""
}, Jsonrequestbehavior.allowget);
HTML page
@{Layout = null;} <! DOCTYPE html>
XMLHttpRequest (native)
function Loginnew () {
var barcode = document.getElementById ("barcode"). Value;
var name = document.getElementById ("name"). Value;
Console.log ("1:" + barcode + "; 2:" + name);
Create asynchronous Object
var xmlhttp = new XMLHttpRequest ();
Sets the type of request and the URL
xmlhttp.open (' Post ', ' http://localhost:52556/api/AssetOa?IsAddAsset=true ', true);
Post requests must be added to the request header to do otherwise the error will be
//xmlhttp.setrequestheader ("Content-type", "Application/json");
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Send Request
//xmlhttp.send (' {"Barcode ': ' + Barcode + ', ' name ': ' + name + '} ');
Xmlhttp.send (' {"barcode= ' + Barcode + ' &name= ' + Name + ' &assettypeid=1} ');
Xmlhttp.onreadystatechange = function () {
//This step is to determine if the server is responding correctly if
(xmlhttp.readystate = 4 && Xmlhttp.status = =) {
console.log (xmlhttp.responsetext);}}
D:\MyFile\ test Project \solution1\webapplication1