Neeraj Neeraj - 4 years ago 264
ASP.NET (C#) Question

Access-Control-Allow-Origin in asp.net web service

I have 2 Project one is Asp.Net Web Service and second is Asp.Net Web Application, When I am trying to run both project in same solution its run perfectly but when we run project separately (on localhost but with port number, I am getting error).
I am hard trying to solve this but no perfect solution got.

WebServiceServer:

[WebMethod]
public void CheckUserNameAndGetNew(string UserName)
{
bool IsUserNameAvailable = true;
DAL dal = new DAL();

UserNameCheck objBel = new UserNameCheck();

//IsUserNameAvailable = dal.CheckUserNameDAL(UserName);

while(!dal.CheckUserNameDAL(UserName)) // get in if UserName already exist in database
{
Random myRandomNum =new Random();
int myRandomNumber = myRandomNum.Next(1, 100);

UserName = UserName + myRandomNumber;
IsUserNameAvailable = false;
}

objBel.IsUserNameAvailable = IsUserNameAvailable;
objBel.UserName = UserName;

JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(objBel));
}


WebServer:

$.ajax({
url: "http://localhost:49839/WebService1.asmx/CheckUserNameAndGetNew",
method: "Post",
data: { UserName: txtUserName },
dataType: "json",
success: function (data) {
debugger;
var AvailableMsg = $('#AvailableMsg');
var Availablelbl = $('#Availablelbl');
var AvailableUserName = $('#AvailableUserName');
if (data.IsUserNameAvailable) {
AvailableMsg.text(txtUserName + ' User Name Available');
Availablelbl.text('');
AvailableUserName.text('');
AvailableMsg.css('color', 'Green');
}
else {
AvailableMsg.text(txtUserName + ' User Name is not Available');
Availablelbl.text('Available: ');
AvailableUserName.text(data.UserName).click(function () {
$('#txtUserName').val($(this).text());
AvailableMsg.text('');
Availablelbl.text('');
AvailableUserName.text('');
});
AvailableMsg.css('color', 'red');
Availablelbl.css('color', 'Gray');
AvailableUserName.css('color', 'green');
}
},
error: function (err) {
debugger;
}
});


Error at client Side Inspect Console:


XMLHttpRequest cannot load
http://localhost:49839/WebService1.asmx/CheckUserNameAndGetNew. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:65360' is therefore not allowed
access.

Answer Source

You need to also allow web service server to provide data cross domain (means also other's call request-response). So for that you need to flowing settings in web.config of your Web Service Server.

 <system.webServer>
 <httpProtocol>
      <customHeaders>
           <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download