如何使WCF Rest服务中的POST方法在传入数据时工作?

时间:2012-02-15 13:27:06

标签: jquery wcf post

当我使用GET方法时,我有一个wcf rest服务它工作正常(它们与url一起传递)。但我需要使用post方法,当post方法没有数据传递时,它工作正常。但是当添加一些数据然后它在IE中返回Bad Request错误并且在mozila和chrome中它只返回ajax jquery请求中的Error。我在这里重新发布了这个问题,因为我无法附加图像。帖子。请帮助...........

我发布了我在wcf服务和ajax方法中使用的代码.pls help ....

Ischeduler.cs中的代码

[ServiceContract]
public interface Ischeduler
{

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "GetData", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    string GetData();

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "GetDataName", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    string GetDataName(string Name);
}

scheduler.cs

public string GetData()
    {
        string getdata = "hello";
        return string.Format("You entered" + getdata);
    }
public string GetDataName(string Name)
    {
        return string.Format("You entered" + Name);
    }

按钮单击

中的Schedular.aspx中的Ajax请求
$("#btnInvoke").click(function () {
                  $.ajax({
                      type: "POST",
                      url: "http://localhost:3125/schedulerAPI_Service/scheduler.svc/GetDataName",
                      data: '{"Name": "John"}',
                      dataType: 'json',
                      contentType: "application/json; charset=utf-8",
                      crossdomain: true,
                      success: function (data) {
                         alert(data);
                      },
                      error: function (xhr, status, error) {
                          alert("failed " + error);
                      }
                  });

Wcf Web Config

<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
        <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
    <connectionStrings>
        <add name="InstaScribeCentralConnectionString" connectionString="Data Source=ATLT53;Initial Catalog=InstaScribeCentral;User ID=sa;Password=bmjobmjo;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehavior">
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="ServiceBehavior">
                    <webHttp/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="ServiceBehavior" name="scheduler">
                <endpoint address="" behaviorConfiguration="ServiceBehavior" binding="webHttpBinding" contract="Ischeduler"/>
            </service>
        </services>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    </system.serviceModel>
</configuration>

enter image description here

3 个答案:

答案 0 :(得分:1)

你有没有像下面这样做,即添加属性到servrice类

   [AspNetCompatibilityRequirements(RequirementsMode 
        = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        // Your code comes here
    }

查看这篇文章,它可以帮助您完成任务:Calling WCF Services using jQuery

修改

查看此帖子也可以帮助您完成任务:Create REST service with WCF and Consume using jQuery

答案 1 :(得分:1)

首先尝试在您的WCF服务上启用Tracing

我在配置中注意到了一些事项:

  1. service元素的name属性值应该是一个完全限定的名称。

  2. endpoint元素具有合同属性值,该值应该是完全限定名称。

  3. 前:

    SampleWCF.Scheduler (i.e. namespace.ServiceName)
    

    请参阅我的示例,以json格式将数据发布到WCF服务:

    我的WCF服务方法:

    [WebInvoke]
    public string GetParam(string Name)
    {
        return Name + " from server";
    }
    

    现在从Fiddler发布一些数据:

    enter image description here

    要传递字符串时,用于发布数据的格式不正确。

答案 2 :(得分:0)

在您的服务上添加异常处理,以准确查看异常。这样,您不仅可以解决此异常,还可以在将来优雅地处理其他异常。

如果您尚未创建配置行,请在Application_Start下的Global.asax文件中添加:

//where config is your WebApiConfiguration/HttpConfiguration file

config.ErrorHandlers = (Handlers, endpoints, descriptions) =>
            {
                Handlers.Add(new CustomErrorHandler(descriptions));
            };

然后创建在类上面添加的异常处理程序:

public class CustomErrorHandler : HttpErrorHandler
{
    public IEnumerable<HttpOperationDescription> Descriptions { get; set; }

    public CustomErrorHandler(IEnumerable<HttpOperationDescription> descriptions)
    {
        Descriptions = descriptions;
    }

    protected override bool OnTryProvideResponse(Exception exception, ref System.Net.Http.HttpResponseMessage message)
    {
        //use exception variable to see what the exception is and then you can either decide
        //to output a response to the user and do nothing further at which point you return true and set the message variable,        or you can just leave it false to return as is.

        return false;
    }
}

另外,你使用什么版本作为WCF Rest现在被称为WCF Web api,据我所知它在0.6上你可以通过NuGet获得?