asp.netfetch-api

Using Fetch in JS to call a server-side method (ASP.NET)


I have an ASPX page, called default.aspx and default.aspx.cs being my code on the server side running on IIS 7, something really simple, written in VS Code. In addition to the JS, CSS and IMG folders (these last two have no relevance to the problem in question).

In the JS file I have a function that makes an HTTP request to the server and it should execute a certain method:

fetch('default.aspx/Enviar_Indicador_Novo',{
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({Data: data_Atualizacao, Pilar: pilar})
})
.then(response => console.log(response))
// .then(message => {console.log(message)})
.catch(error => {
    console.log(error)
})

and:

[WebMethod]
public string Enviar_Indicador_Novo(string Data, string Pilar){
    ... metodo a ser executado e retornar uma string de "sucesso" ou "falha""
}

At the beginning of my ASPX file, I put the tag: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="Buscar_SQL.Index" %>

Busca_SQL is my namespace and Index is my partial class.

the response to this request is this: Response {type: 'basic', url: 'http://xxx.xxx.xxx.xxx/xxxx/default.aspx/Enviar_Indicador_Novo', redirected: false, status: 200, ok: true , …}

The issue is, it does not execute the method on the server side, it only reports the response with status 200, even though it does not execute the method.

Can you help me? Is it some config in my IIS? The only thing I did with it was host and configure it to run ASPX pages.

I checked the request route and it is correct, I put the method with public static string ... and it didn't work either.


Solution

  • I not (yet) used fetch, but what you have does look correct.

    Keep in mind that since you are NOT using a asmx page, but a regular aspx page with a webmethod?

    Then your web method has to be static, since a whole instance of the page (code behind) class is not being created.

    Hence, try this:

    [WebMethod]
     public static string Enviar_Indicador_Novo(string Data, string Pilar)
     {
        ... metodo a ser executado e retornar uma string de "sucesso" ou "falha""
      }
    

    You also don't show in your JavaScript code where and how you set the two variables, but we have to assume they are ok, and have been setup correctly.

    In addition to the above, I do suggest you check your settings in RouteConfig.cs, since you want to turn off AutoRedirect mode:

            settings.AutoRedirectMode = RedirectMode.Off;