大神有没有?看看ajax post 数据到WCF为啥总报405或跨域?

一个WCF测试例子,使用jquery调用方法.。为啥POST就不可以?

代码下载链接

IAjaxServic.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;

namespace WcfService1
{
    [ServiceContract(Namespace = "www.yycode.net", Name = "MyTestService")]
    public interface IAjaxServic
    {
        [OperationContract]
        void DoWork();

        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string MyFirstWCFFunction();

        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string MySecondWCFFunction(string name);

        [OperationContract]
        [WebInvoke(UriTemplate = "/aaabbb", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string MySecondWCFFunction2(UserInfo user, string id);

    }
}

AjaxService.svc

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{


    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [JavascriptCallbackBehavior(UrlParameterName ="jsoncallback")]
    public class AjaxService : IAjaxServic
    {
        // 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
        // 要创建返回 XML 的操作,
        //     请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     并在操作正文中包括以下行:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

        public void DoWork()
        {
            // 在此处添加操作实现
            return;
        }


        public string MyFirstWCFFunction()
        {
            return "aaabbb";
        }

        public string MySecondWCFFunction(string name)
        {
            string strMsg = string.Format("我的第二个WCF方法~", name);

            // 在此处添加操作实现
            return strMsg;
        }



        public string MySecondWCFFunction2(UserInfo user, string id)
        {
            return "bbb";
            string strMsg = string.Format("test post", user.ToString());

            // 在此处添加操作实现
            return strMsg;
        }

        // 在此处添加更多操作并使用 [OperationContract] 标记它们
    }
}

配置文件web.config与 app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
  <system.serviceModel>
    <diagnostics performanceCounters="Default" />
    <bindings>
      <webHttpBinding>
        <binding name="AjaxServiceBinding" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfService1.AjaxService">
        <endpoint address="" behaviorConfiguration="WcfService1.AjaxServiceAspNetAjaxBehavior"
          binding="webHttpBinding" bindingConfiguration="AjaxServiceBinding"
          name="AjaxService1" contract="WcfService1.IAjaxServic" />
        <host>
          <baseAddresses>
            <add baseAddress="http://127.0.0.1:17517/AjaxService.svc" />
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="WcfService1.AjaxServiceAspNetAjaxBehavior">
          <webHttp />
          <!--<enableWebScript />-->
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
        在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
      -->
    <directoryBrowse enabled="true"/>

    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
        <add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>



  </system.webServer>

</configuration>

 

然后HOST到Winform

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WCF_TEST
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ServiceHost m_Host = null;

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                m_Host = new ServiceHost(typeof(WcfService1.AjaxService));
                if (m_Host.State != CommunicationState.Opened)
                {
                    m_Host.Open();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

另一项目jQUERY调用


            $(document).ready(function () {

                $("#Button1").click(function () {

                    $.ajax({
                        type: "GET",
                        url: "http://localhost:17517/AjaxService.svc/MyFirstWCFFunction?jsoncallback=?",
                        dataType: "json",
                        data: {},
                        
                        //contentType: 'application/json; charset=utf-8',
                        //async: false,//非异步
                        //crossDomain: true,
                        success: function (data) {
                            console.log(data);
                        },
                        error: function (str, txtStatus, mes) {
                            alert(txtStatus + mes);
                        }
                    });

                });


                $("#Button2").click(function () {
                    $.ajax({
                        type: "POST",//Post方式
                        data: { name: '南宫萧尘' },
                        dataType: "json",
                        contentType: 'application/json; charset=utf-8',
                        async: false,//非异步
                        url: "http://localhost:17517/AjaxService.svc/MySecondWCFFunction?jsoncallback=?",
                        success: function (data, status) {
                            console.log(data);
                            alert(data + status);
                        },
                        error: function (str, txtStatus, mes) {
                            alert(txtStatus + mes);
                            //alert(mes);
                        }
                    });
                });

                var user1 = { "user": { "name": "Bill", "sex": "Gates" } };
                var user2 = { "name": "Bill", "sex": "Gates" };
                var users2 = {
                    "users": [
                        { "name": "Bill", "sex": "Gates" },
                        { "name": "Thomas", "sex": "Carter" }
                    ]
                };
                $("#Button3").click(function () {
                    $.ajax({
                        //cache: false,
                        //async: false,
                        type: "POST",
                        url: "http://localhost:17517/AjaxService.svc/aaabbb",
                        data: JSON.stringify(user1),
                        contentType: 'application/x-www-form-urlencoded',
                        dataType: "text",
                        processData: false,
                        success: function (data, status) {
                            console.log(data);
                            alert(data + status);
                        },
                        error: function (str, txtStatus, mes) {
                            alert(txtStatus + mes);
                            //alert(mes);
                        }
                    });
                });

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵之章

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值