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

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

问题描述

我创建了一个简单的C#WCF服务,该服务返回带有html代码的字符串。当我在WCF解决方案中通过简单的MVC项目使用此服务时,everythigs都可以正常工作。




  • 服务代码



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




  • 接口代码



  [ServiceContract] 
公共接口IConnectorService
{
[ OperationContract]
字符串GetData();
}

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




  • 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:应用程序/ json; charset = utf-8,
类型: GET,
dataType: jsonp,
成功:函数(数据){
$('#divContent')。html(data);
},
错误:function(error){
alert( error:status- + error.status + | text: + error.statusText);
}
});

});
< / script>

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



1)CORS政策-我使用以下global.asax文件修复了该问题

 受保护的无效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代码



 <?xml版本= 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>
<行为>
< serviceBehaviors>
<行为>
<!-为避免泄露元数据信息,请在部署前将以下值设置为false。
< serviceMetadata httpGetEnabled = true httpsGetEnabled = true />
<!-要在故障中接收异常详细信息以进行调试,请将下面的值设置为true。在部署之前设置为false以避免泄露异常信息->
< serviceDebug includeExceptionDetailInFaults = true />
< / behavior>
< / serviceBehaviors>
< / behaviors>
< protocolMapping>
< add binding = basicHttpsBinding scheme = https />
< / protocolMapping>
< serviceHostingEnvironment aspNetCompatibilityEnabled = true multipleSiteBindingsEnabled = true />
< /system.serviceModel>
< system.webServer>

< httpProtocol>
< customHeaders>
<添加名称= 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>

<模块runAllManagedModulesForAllRequests = true />
<!-
要在调试期间浏览Web应用程序的根目录,请将下面的值设置为true。
在部署之前设置为false,以避免泄露Web应用程序文件夹信息。
->
< directoryBrowse enabled = true />
< /system.webServer>

< / configuration>

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



预先感谢。

解决方案

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

  $。 ajax({
url:'http://localhost/ConnectorService.svc/GetData',
contentType:'application / json; charset = utf-8',
type: GET ,
dataType:'jsonp',
成功:函数(数据){
$('#divContent')。html(data);
},
错误:函数(错误){
alert(错误:状态- + error.status + |文本: + error.statusText);
}

这种通过直接发送http请求来调用服务的样式通常适用于Restful样式服务,请参阅以下链接。



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

  $。ajax({
方法:获取,
网址: http://10.157.13.69:11000/Service1.svc/GetData?value=34 ,
contentType: application / json
})。done(function(data){
console.log(data);
})

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


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天全站免登陆