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

daowdos 296 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: '******@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

Developer technologies ASP.NET ASP.NET Core
Windows development Windows API - Win32
Windows for business Windows Server User experience Other
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

Accepted answer
  1. daowdos 296 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. AgaveJoe 30,126 Reputation points
    2021-08-29T13:30:49.96+00:00

    I don't use JQuery so I merge the postData() function there it mae it into one.

    Huh? postData is a function that I copied directly from Using fetch API on MDN. The only jQuery is a button click handler that invokes the function. In React you would just call the function.

    With all the changes you made I still get the same error.

    You misunderstand the GitHub repo intent. There are no code changes. Several weeks ago I provided three patterns in a Githib repo. The first pattern is intended to illustrate why returning a JSON string in an XML response is a poor design. Either you did not understand the intent or you are mindlessly copying and pasting code hoping something will magically work. I assume the later.

    The second pattern, the pattern I posted above, illustrates how to fix your original Web Method design and return an actual type. It also alerts that the JSON data is wrapped within a "d" object. This is a convention used in ASMX which is not standard in today's REST services. You MUST fix your poorly designed Web Method to use the second pattern!!!

    Lastly, I shared the recommended approach using Web API and Swagger documentation. Which allows you to interact with every action through a documentation pages.

    The intent of the examples was to get you to the final pattern which is a modern REST service pattern. Clearly, that failed.

    I don't know hat is wrong with the fetch.

    The community needs the Web Method signature, model, and client code. Otherwise, the community cannot find the mistakes in your code base.


  2. MotoX80 36,291 Reputation points
    2021-09-01T13:26:47.377+00:00

    I've tried to wade through all of the replies on this thread and I apologize if I missed something, but the one thing that I don't see is any server side troubleshooting. If IIS is crashing on the request, you need to review the log files on the server.

    Default location is C:\inetpub\logs\LogFiles with a W3SVC subfolder for the site. What entries do you see for the 500 status code?

    Also check the HTTP error log files in C:\Windows\System32\LogFiles\HTTPERR

    I would also recommend enabling failed request tracing for the 500 status code. That will capture the error in XML files in C:\inetpub\logs\FailedReqLogFiles\W3SVCx. (Again default folder.)

    https://learn.microsoft.com/en-us/iis/troubleshoot/using-failed-request-tracing/troubleshooting-failed-requests-using-tracing-in-iis-85

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.