Passing data to Web Service ASP.NET - Getting 500 (Internal Server Error)

daowdos 261 Reputation points
2021-08-25T20:21:11.673+00:00

I have an issue with fetching and passing data to ASP.NET web service from the ReactJS.

Other fetch function is working with only getting data from the database.
Why am I getting these errors ? what am I doing here wrong ?
I believe its something in my signUp fetch function.

That response I think is that the fetch can't read the response from the server -

main.chunk.js:2417 POST http://localhost:50496/WebService.asmx/SignUp 500 (Internal Server Error)  


SyntaxError: Unexpected token T in JSON at position 0  at JSON.parse (<anonymous>)  
userData = {  
    fName: 'popv',  
    lName: 'lelemb',  
    email: 'eyafff@gmail.com',  
    password: '123123'  }  

My fetch function in ReactJs -

   const signUp = (signUpData) => {  

    let data = {  
      firstName: signUpData.fName,  
      lastName: signUpData.lName,  
      emailAddress: signUpData.email,  
      password: signUpData.password,  
    };  
    fetch('http://localhost:50496/WebService.asmx/SignUp', {  
      body: JSON.stringify(data),  
      method: 'POST',  
      headers: {  
        'Content-Type': 'application/json; charset=UTF-8',  
      },  
    })  
      .then((response) => response.text())  
      .then(  
        (xml) =>  
          new window.DOMParser().parseFromString(xml, 'text/xml')  
            .documentElement.firstChild.textContent  
      )  
      .then((jsonStr) => JSON.parse(jsonStr))  
      .then((userData) => {  
        if (userData.d  && userData.d.length > 0) {  
          setUser(userData);  
        } else {  
          console.log('error no data');  
        }  
      })  
      .catch((err) => {  
        console.log(err);  
      });  
  };  

DevTools error in Chrome -

System.InvalidOperationException: missing parameter : firstName.
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request)
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

SignUp WebMethod is working in the WebService.

[WebMethod]  
public string SignUp(string firstName, string lastName, string emailAddress, string password)  
{  
   return BLL.SignUp(firstName, lastName, emailAddress, password);  
}  

126841-header.png

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,080 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,222 questions
Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
11,935 questions
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,389 questions
0 comments No comments
{count} votes

Accepted answer
  1. daowdos 261 Reputation points
    2021-09-05T07:44:51.147+00:00

    Hi everyone @Limitless Technology and @MotoX80
    I found the solution,
    I searched deeper in dev-tools for the error and found -

    InvalidOperationException: Only web services with the [ScriptService] attribute in the class definition can be read from a script.

    Than I searched for it and found the solution so I added in C# the Attribute Class [ScriptService] to WebService.cs

     [WebService(Namespace = "http://tempuri.org/")]  
     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
     [ScriptService]  
    

    I changed the fetch method to work -

     fetch('http://localhost:50496/WebService.asmx/SignUp', {  
          body: JSON.stringify(data),  
          method: 'POST',  
          headers: {  
            'Content-Type': 'application/json',  
          },  
        })  
          .then((response) => response.json())  
          .then((userData) => {  
            if (userData.d && userData.d.length > 0) {  
              console.log('userData', userData);  
              let user = JSON.parse(userData.d);  
              setUserData(user);  
              history.push('/');  
            } else {  
              console.log('error not good');  
            }  
          })  
          .catch((err) => {  
            console.log('err', err);  
          });  
    

    and now it's working great.

    Thanks.

    0 comments No comments

6 additional answers

Sort by: Most helpful
  1. Limitless Technology 39,301 Reputation points
    2021-09-01T12:40:22.597+00:00

    Hi again ,

    I suppose Only web services which has the [ScriptService] attribute in the class definition can be read from a script but it seems your code is missing to fetch this and can you try adding specific attributes to it.

    Hope this Answers all your queries , if not please do repost back .
    If an Answer is helpful, please click "Accept Answer" and upvote it : )

    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 53,501 Reputation points
    2021-08-25T21:52:24.097+00:00

    your post to the server is failing (getting a 500 error). the response is probably an html error page, but your code tries to parse the first dom element as json. (sticking json in a xml node is bad practice)

    note: a 500 error is a valid html response, so no error is thrown. you should be checking the response status.

        .then((response) => {
             if (!response.ok) 
                 throw (`bad response ${response.status} - ${response.statusText}`);
             return response.text()
         })
    

  3. Limitless Technology 39,301 Reputation points
    2021-08-26T14:29:19.463+00:00

    Hello Elado,

    Thank you for your question.

    Please follow these steps, it will help you:

    You need to make changes to your browser configuration.

    2.Open Internet Explorer, select the Internet Options menu item and open the Security tab of the popup window.
    3. Click the Local intranet icon and then click the Sites button and a new window will open.
    4. Click the Advanced Button and a new window will open.
    5. Enter the URL in the upper input box, click the Add button. Then enter a URL and click the Add button again. Then click the Close button and then click OK out of the
    previous window.
    6. Select the Security tab at the top then select Custom Level again. Scroll down to User Authentication and select Automatic logon with current user name and
    password. When finished select OK.
    7. Select the Advanced tab at the top then select the box Enable Integrated Windows Authentication* and click Apply.
    8. Restart.

    If the reply was helpful, please don't forget to upvote or accept as answer.

    Thanks,


  4. AgaveJoe 25,866 Reputation points
    2021-08-27T14:00:21.013+00:00

    Did all the steps nothing works

    The steps provided by LimitlessTechnology-2700 assumes you are using Windows Authentication. Even if you were, the steps will not fix the fetch error. The main issue you face is not listening to the advice given on these forums of follow any working examples. Below is the same code pattern I've proved several times. I'm not sure what else we can do for you...

    Also, please follow the troubleshooting recommendations in this thread. Review the response tab located in network trace utility within the Brower's dev tools. The response often contains the actual error returned from the service like a missing parameter.

    127109-capture.png

    public class LoginModel  
    {  
        public string Email { get; set; }  
        public string Password { get; set; }  
    }  
    

    Web Method

    [WebMethod]  
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
    public int? Login(LoginModel login)  
    {  
        return Bll.Login(login);  
    }  
    

    Script

    $('#Button1').click(function () {  
        postData('http://localhost:63579/WebService.asmx/login', {  
            'login': {  
                "Email": $('#Email').val(),  
                "Password": $('#Password').val()  
            }  
        })  
            .then(data => {  
                console.log(data);  
                $('#results').text("Id = " + data.d);  
            });  
    });  
      
    // Example POST method implementation:  
    async function postData(url = '', data = {}) {  
        console.log(JSON.stringify(data));  
      
        // Default options are marked with *  
        const response = await fetch(url, {  
            method: 'POST', // *GET, POST, PUT, DELETE, etc.  
            mode: 'cors', // no-cors, *cors, same-origin  
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached  
            credentials: 'same-origin', // include, *same-origin, omit  
            headers: {  
                'Content-Type': 'application/json'  
                //'Content-Type': 'application/x-www-form-urlencoded',  
            },  
            redirect: 'follow', // manual, *follow, error  
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url  
            body: JSON.stringify(data) // body data type must match "Content-Type" header  
        });  
        return response.json(); // parses JSON response into native JavaScript objects  
    }  
    

    Markup

    <div class="row">  
        <div class="col-md-6">  
            <form>  
                <div class="form-group">  
                    <label for="Email">Email</label>  
                    <input type="text" class="form-control" id="Email" value="eyafff@gmail.com">  
                </div>  
                <div class="form-group">  
                    <label for="Password">Password</label>  
                    <input type="text" class="form-control" id="Password" value="123123">  
                </div>  
                <button id="Button1" type="button" class="btn btn-primary">Submit</button>  
            </form>  
        </div>  
        <div class="col-md-6">  
            <h2>Results</h2>  
            <div id="results">  
      
            </div>  
        </div>  
    </div>  
    

    DataAccess

    public int? Login(LoginModel login)  
    {  
        string queryString = @"SELECT Id  
                                FROM UserData  
                                WHERE Email = @Email   
                                    AND [Password] = @Password";  
      
        using (SqlConnection connection = new SqlConnection(ConnectionString))  
        {  
            SqlCommand command = new SqlCommand(queryString, connection);  
            command.CommandType = CommandType.Text;  
            command.Parameters.AddWithValue("@Email", login.Email);  
            command.Parameters.AddWithValue("@Password", login.Password);  
            connection.Open();  
      
            return (int?)command.ExecuteScalar();  
        }  
    }