Неизвестная ошибка веб-метода из AJAX вызова веб-методов в локальном хосте веб-формы - PullRequest
0 голосов
/ 11 марта 2020

У меня странная проблема, когда у меня есть два веб-метода в классе веб-формы, они вызываются JQuery AJAX, но я получаю Неизвестную ошибку веб-метода. Я попытался сделать webmethods publi c и stati c, но не могу заставить это работать. Я проверяю это локально. Может кто-нибудь помочь, пожалуйста, спасибо!

aspx

public partial class PBXservice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public class PBXservices : System.Web.Services.WebService
   {
        [WebMethod]
        public static string service(string data)
        {
            //connect client to url where SignalR server is listening
            var hubConnection = new HubConnection("http://localhost:8081/");
            var serverHub = hubConnection.CreateHubProxy("WebHub");

            //start Hub and wait to finish connecting
            hubConnection.Start().Wait();

            //call Hub with Invoke, pass name and argument
            serverHub.Invoke("Connect", "PBXWebApp");
            // string line = null;
            while ((data = System.Console.ReadLine()) != null)
            {
                // send message to the server
                serverHub.Invoke("SendPBXData", data, "PBXWebApp").Wait();
            }
            return data;
        }

        [System.Web.Services.WebMethod]
        public static string GetData()
        {
            return DateTime.Now.ToString();
        }
    }

}

AJAX

   var pbxdata = "Hi there!";
        jQuery.ajax({
            url: 'PBXservice.aspx/service',
            type: "POST",
            dataType: "json",
            data: "{'pbxdata': '" + pbxdata + "'}",
            contentType: "application/json; charset=utf-8", 
            success: function (data) {
                alert(JSON.stringify(data));
            }
        });




 $.ajax({  
          type: "POST",  
          url: "PBXservice.aspx/GetData",  
          data: '',  
          contentType: "application/json; charset=utf-8",  
          dataType: "json",  
          success: function (response) {  
              alert(response.d);  
          },  
 });  

web config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.5" />
      </system.Web>
  -->
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <pages controlRenderingCompatibilityVersion="4.0" />
  </system.web>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
<system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer></configuration>

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Мне пришлось изменить атрибут Codebehind на CodeFile, вот и все!

CodeBehind = "PBXservice.aspx.cs"

на

CodeFile = "PBXservice. aspx.cs "

Сообщение об ошибке анализатора: не удалось загрузить тип 'webmarketing'

Спасибо всем за публикацию!

0 голосов
/ 11 марта 2020

Доброе утро. Вам действительно нужен этот класс "PBXservices"? Вы можете поместить методы "service" и "GetData" непосредственно в "PBXservice". Затем измените конфигурацию в "App_Code \ RouteConfig.cs": OLD: "settings.AutoRedirectMode = RedirectMode.Permanent" NEW: "settings.AutoRedirectMode = RedirectMode.Off".

ASPX.CS


    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Method intentionally left empty.
        }

        [WebMethod]
        public static string GetData()
        {
            return DateTime.Now.ToString();
        }
    }

ASPX (HTML)


     
        $(document).ready(function () {
            $('#bntAjax').click(CallAjax);
        });

        function CallAjax() {
            $.ajax({
                type: "POST",
                url: "PBXservices/GetData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    console.log(response);
                },
            });
        }
    

App_Code \ RouteConfig.cs

    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Off;
            routes.EnableFriendlyUrls(settings);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...