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

Access-Control-Allow-Origin in 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.


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


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

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

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.

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