简体   繁体   English

如何通过Jquery调用C#WCF服务来解决“ ERR_ABORTED 400(错误请求)”错误?

[英]How to fix “ERR_ABORTED 400 (Bad Request)” error with Jquery call to C# WCF service?

I created a simple C# WCF service that returns a string with html code. 我创建了一个简单的C#WCF服务,该服务返回带有html代码的字符串。 When i consume this service with a simple MVC project inside the WCF solution, everythigs works fine. 当我在WCF解决方案中通过简单的MVC项目使用此服务时,everythigs可以正常工作。

  • Service code 服务编号
    public class ConnectorService : IConnectorService
    {
        public string GetData()
        {
            return "<a href='www.test.com.br'>test</a>";
        }
    }
  • Interface code 接口代码
    [ServiceContract]
    public interface IConnectorService
    {
        [OperationContract]
        string GetData();
    }

After this test i published this service in my local IIS and tried to consume this service with a html page that is not inside the WCF solution, but is located inside the same IIS directory of the service. 测试完成后,我在本地IIS中发布了该服务,并尝试使用不在WCF解决方案内部但位于该服务的同一IIS目录中的html页面使用该服务。

  • HTML code HTML代码
    <html>
        <head>
        <title>test</title>
        <script src='Scripts/jquery-3.3.1.min.js'></script>
        </head>
    <body>
        <div id='divContent'></div>
    </body>
    </html>

    <script type='text/javascript'>
        $(document).ready(function () {

            $.ajax({
                url: 'http://localhost/ConnectorService.svc/GetData',
                contentType: 'application/json; charset=utf-8',
                type: "GET",
                dataType: 'jsonp',
            success: function (data) {
                $('#divContent').html(data); 
            },
            error: function (error) {
                alert("error:  status - " + error.status + " | text: " + error.statusText);
            }
        });

    });
    </script>

When i open this html file on the browser, I got 2 errors: 当我在浏览器中打开此html文件时,出现2个错误:

1) CORS policy - i fixed that with global.asax file like this 1)CORS政策-我使用global.asax文件修复了该问题

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

2) Error 400 - Bad Request I tried several solutions of stack overflow, generally with changes on my ajax call, global.asax and web.config file, but i always get a bad request error inside the chrome console. 2)错误400-错误的请求我尝试了几种堆栈溢出的解决方案,通常对ajax调用,global.asax和web.config文件进行了更改,但是在chrome控制台中总是出现错误的请求错误。

  • web.config code web.config代码
        <?xml version="1.0"?>
    <configuration>

      <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2"/>
      </system.web>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <protocolMapping>
          <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
      <system.webServer>

        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Credentials" value="true" />
            <add name="Access-Control-Allow-Headers" value="Content-Type,Accept" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
          </customHeaders>
        </httpProtocol>

        <modules runAllManagedModulesForAllRequests="true"/>
        <!--
            To browse web app root directory during debugging, set the value below to true.
            Set to false before deployment to avoid disclosing web app folder information.
          -->
        <directoryBrowse enabled="true"/>
      </system.webServer>

    </configuration>

I believe this is a simple problem with a simple solution but, after several days of tests, i feel that i am chasing my own tail. 我相信这是一个简单的问题,有一个简单的解决方案,但是经过几天的测试,我觉得自己正在追逐自己的尾巴。 Can someome point me with a solution for this? 有人可以为此提供解决方案吗?

Thanks in advance. 提前致谢。

There is something wrong with the invocation. 调用有问题。 Normally, we call the typical WCF service by using client proxy class instead of directly sending an http request. 通常,我们通过使用客户端代理类而不是直接发送http请求来调用典型的WCF服务。

$.ajax({
            url: 'http://localhost/ConnectorService.svc/GetData',
            contentType: 'application/json; charset=utf-8',
            type: "GET",
            dataType: 'jsonp',
        success: function (data) {
            $('#divContent').html(data); 
        },
        error: function (error) {
            alert("error:  status - " + error.status + " | text: " + error.statusText);
        }

This style calling the service by directly sending http request usually applies to the Restful Style Service, please refer to the below link. 这种通过直接发送http请求来调用服务的样式通常适用于Restful样式服务,请参考以下链接。
https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design
Both Asp.net WebAPI and WCF could create a Restful style service. Asp.net WebAPI和WCF都可以创建Restful样式服务。
https://docs.microsoft.com/en-us/aspnet/web-api/ https://docs.microsoft.com/en-us/aspnet/web-api/
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/wcf-web-http-programming-model-overview https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/wcf-web-http-programming-model-overview
Based on your example, we could change the WCF service to Restful style, and then we could call it by directly sending an http request. 根据您的示例,我们可以将WCF服务更改为Restful样式,然后我们可以通过直接发送http请求来调用它。
Interface. 接口。

        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            [WebGet(RequestFormat =WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)]                    
            string GetData(int value);

    }

Service. 服务。

public class Service1 : IService1
{

    public string GetData(int value)
    {
        return "<a href='www.test.com.br'>test</a>";
    }
}

Web.config Web.config文件

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <protocolMapping>
      <add scheme="http" binding="webHttpBinding"/>
    </protocolMapping>
  </system.serviceModel>

Result (accessing the URL with typing the address in browser is Http Get request). 结果(通过在浏览器中键入地址来访问URL是Http Get请求)。
在此处输入图片说明
Alternatively, we call it by sending Ajax request. 另外,我们通过发送Ajax请求来调用它。

$.ajax({
    method:"Get",
    url: "http://10.157.13.69:11000/Service1.svc/GetData?value=34",
    contentType:"application/json"
}).done(function(data){
    console.log(data);
})

Feel free to let me know if there is anything I can help with. 请随时告诉我是否有什么我可以帮助的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM