如何修复“ERR_ABORTED 400(错误请求)"Jquery 调用 C# WCF 服务时出错? [英] How to fix "ERR_ABORTED 400 (Bad Request)" error with Jquery call to C# WCF service?

查看:36
本文介绍了如何修复“ERR_ABORTED 400(错误请求)"Jquery 调用 C# WCF 服务时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 C# WCF 服务,它返回一个带有 html 代码的字符串.当我在 WCF 解决方案中使用一个简单的 MVC 项目使用此服务时,一切正常.

  • 服务代码

 公共类 ConnectorService : IConnectorService{公共字符串 GetData(){return "<a href='www.test.com.br'>test</a>";}}

  • 接口代码

 [ServiceContract]公共接口 IConnectorService{【经营合同】字符串获取数据();}

在此测试后,我在本地 IIS 中发布了此服务,并尝试使用不在 WCF 解决方案中但位于该服务的同一 IIS 目录中的 html 页面使用此服务.

  • HTML 代码

 <头><title>test</title><script src='Scripts/jquery-3.3.1.min.js'></script><身体><div id='divContent'></div><script type='text/javascript'>$(document).ready(function () {$.ajax({url: 'http://localhost/ConnectorService.svc/GetData',contentType: '应用程序/json;字符集=utf-8',类型:获取",数据类型:'jsonp',成功:功能(数据){$('#divContent').html(data);},错误:函数(错误){alert("错误:状态 - " + error.status + " | text: " + error.statusText);}});});

当我在浏览器上打开这个 html 文件时,出现 2 个错误:

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) 错误 400 - 错误请求我尝试了几种堆栈溢出的解决方案,通常会更改我的 ajax 调用、global.asax 和 web.config 文件,但我总是在 chrome 控制台中收到错误的请求错误.

  • web.config 代码

 <配置><应用设置><add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/></appSettings><system.web><编译调试="true" targetFramework="4.7.2"/><httpRuntime targetFramework="4.7.2"/></system.web><system.serviceModel><行为><服务行为><行为><!-- 为避免泄露元数据信息,请在部署前将以下值设置为 false --><serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/><!-- 要接收故障中的异常详细信息以进行调试,请将以下值设置为 true.在部署前设置为 false 以避免泄露异常信息 --><serviceDebug includeExceptionDetailInFaults="true"/></行为></serviceBehaviors></行为><协议映射><add binding="basicHttpsBinding" scheme="https"/></protocolMapping><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/></system.serviceModel><system.webServer><http协议><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></http协议><modules runAllManagedModulesForAllRequests="true"/><!--要在调试期间浏览 Web 应用程序根目录,请将以下值设置为 true.在部署之前设置为 false 以避免泄露 Web 应用程序文件夹信息.--><directoryBrowse enabled="true"/></system.webServer></配置>

我相信这是一个简单的问题,有一个简单的解决方案,但经过几天的测试,我觉得我在追逐自己的尾巴.有人可以为我指出解决方案吗?

提前致谢.

解决方案

调用有问题.通常,我们使用客户端代理类而不是直接发送http请求来调用典型的WCF服务.

$.ajax({url: 'http://localhost/ConnectorService.svc/GetData',contentType: '应用程序/json;字符集=utf-8',类型:获取",数据类型:'jsonp',成功:功能(数据){$('#divContent').html(data);},错误:函数(错误){alert("错误:状态 - " + error.status + " | text: " + error.statusText);}

这种直接发送http请求来调用服务的风格通常适用于Restful Style Service,请参考以下链接.

或者,我们通过发送 Ajax 请求来调用它.

$.ajax({方法:获取",url: "http://10.157.13.69:11000/Service1.svc/GetData?value=34",内容类型:应用程序/json"}).完成(功能(数据){控制台日志(数据);})

如果有什么我可以帮忙的,请随时告诉我.

I created a simple C# WCF service that returns a string with html code. When i consume this service with a simple MVC project inside the WCF solution, everythigs works fine.

  • 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.

  • HTML code

    <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:

1) CORS policy - i fixed that with global.asax file like this

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.

  • web.config code

        <?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.

$.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.
https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design
Both Asp.net WebAPI and WCF could create a Restful style service.
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
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.
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

  <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).

Alternatively, we call it by sending Ajax request.

$.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.

这篇关于如何修复“ERR_ABORTED 400(错误请求)"Jquery 调用 C# WCF 服务时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆