WCF REST服务和jQuery Ajax的帖子:不允许的方法 [英] wcf REST Services and JQuery Ajax Post: Method not allowed

查看:177
本文介绍了WCF REST服务和jQuery Ajax的帖子:不允许的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道这有什么错呢?我无法从我的WCF REST服务的JSON响应。

jQuery的



$阿贾克斯({
  键入:POST,
  网址:HTTP://本地主机:8090 / UserService的/的ValidateUser
  数据:{用户名:新用户,密码:PWD},
  的contentType:应用/ JSON的;字符集= UTF-8,
  成功:函数(MSG){
   警报(味精);
  },

  错误:函数(XHR,ajaxOptions,thrownError){
   警报('错误');
  }

});


服务



  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)
    公共类UserService的:IUserService
    {
        私人只读IUserRepository _repository;

        公共UserService的()
        {
            _repository =新UserRepository();
        }

        公共ServiceObject的ValidateUser(用户名字符串,字符串密码)
        {
           //执行
        }
    }

    [的ServiceContract]
    公共接口IUserService
    {
        [WebInvoke(方法=POST,ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)
        [OperationContract的]
        ServiceObject的ValidateUser(用户名字符串,字符串密码);
    }


web配置



 < system.serviceModel>

    <! - 行为在这里.-->
    <行为>
      < endpointBehaviors>
        <行为NAME =defaultEndpointBehavior>
          < webHttp />
        < /行为>
      < / endpointBehaviors>

      < serviceBehaviors>
        <行为NAME =>
          < serviceMetadata httpGetEnabled =真/>
          < serviceDebug includeExceptionDetailInFaults =FALSE/>
        < /行为>
      < / serviceBehaviors>
    < /行为>
    <! - 行为结束 - >

    <! - 这里的服务 - >
   <服务>
      <服务名称=MyWcf.Services.UserService>
        <端点地址=UserService的behaviorConfiguration =defaultEndpointBehavior
          绑定=的WebHttpBinding合同=MyWcf.Services.IUserService/>
      < /服务>
    < /服务>

    <! - 服务结束 - >

    < serviceHostingEnvironment aspNetCompatibilityEnabled =真/>
    < standardEndpoints>
      < webHttpEndpoint>
        < standardEndpoint NAME =
                          helpEnabled =真
                          automaticFormatSelectionEnabled =真
                          defaultOutgoingResponseFormat =的Json
                          crossDomainScriptAccessEnabled =真/>
      < / webHttpEndpoint>
    < / standardEndpoints>
  < /system.serviceModel>


解决方案

我看到你的code多的问题:

405意味着不允许方法 - 这可能意味着你发送的数据错误的资源。你确定你的地址是正确的?你如何公开服务?它是 .SVC 文件或 ServiceRoute ?如果是 .SVC 文件中的地址将是 UserService.svc / UserService的/的ValidateUser

  • UserService.svc,因为这是入口点服务(如果您使用的是 ServiceRoute 您可以重新定义该
  • UserService的,因为你是在端点配置定义这个相对地址
  • 的ValidateUser,因为这是默认入口点为您的操作

现在你的JSON请求完全是坏的,你的方法签名为好。类似的方法签名服务合同必须准备一个JSON对象=它必须是一个数据的合同:

  [DataContract]
公共类的UserData
{
    [数据成员]
    公共字符串用户名{获得;组; }

    [数据成员]
    公共字符串密码{获得;组; }
}
 

和操作特征将是:

  [WebInvoke(方法=POST,BodyStyle = WebMessageBodyStyle.Bare)
[OperationContract的]
ServiceObject的ValidateUser(的UserData USERDATA);
 

有一个在JSON请求没有包装元素,正因为如此,你必须使用。此外,它不需要设置响应格式,因为你将在端点级别设置(顺便说一句,你还必须设置要求的格式,如果你不这样做)。

一旦你定义的数据合同,你的要求,你必须正确地定义AJAX请求本身:

  $。阿贾克斯({
  键入:POST,
  网址:UserService.svc / UserService的/的ValidateUser
  数据:{用户名:新用户,密码:PWD}
  的contentType:应用/ JSON的;字符集= UTF-8,
  成功:函数(MSG){
    警报(味精);
  },

  错误:函数(XHR,ajaxOptions,thrownError){
    警报('错误');
  }

});
 

JSON对象是作为字符串!和它的所有成员以及!

有关最后修改配置为:

 < system.serviceModel>
  <服务>
    <服务名称=UserService.UserService>
      <端点地址=UserService的KIND =webHttpEndpoint合同=UserService.IUserService/>
    < /服务>
  < /服务>
  < serviceHostingEnvironment aspNetCompatibilityEnabled =真/>
  < standardEndpoints>
    < webHttpEndpoint>
      < standardEndpoint helpEnabled =真automaticFormatSelectionEnabled =真/>
    < / webHttpEndpoint>
  < / standardEndpoints>
< /system.serviceModel>
 

如果你想使用 standardEndpoint 必须使用实物的端点定义,你不需要指定行为(这是普通终端的一部分)。您也没有使用跨域调用,这样你就不需要启用他们,你不需要默认格式,因为它是自动解决。

Anyone knows what's wrong with this? I cant get the json response from my wcf rest service.

Jquery



$.ajax({
  type: 'POST',
  url: "http://localhost:8090/UserService/ValidateUser",
  data: {username: 'newuser', password: 'pwd'},
  contentType: "application/json; charset=utf-8",
  success: function(msg) {
   alert(msg);
  },

  error: function(xhr, ajaxOptions, thrownError) {
   alert('error');
  }

});


Service



  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class UserService: IUserService
    {
        private readonly IUserRepository _repository;

        public UserService()
        {
            _repository = new UserRepository();
        }

        public ServiceObject ValidateUser(string username, string password)
        {
           //implementation
        }
    }

    [ServiceContract]
    public interface IUserService
    {
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        [OperationContract]
        ServiceObject ValidateUser(string username, string password);
    }


web config



 <system.serviceModel>

    <!--Behaviors here.-->
    <behaviors>
      <endpointBehaviors>
        <behavior name="defaultEndpointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!--End of Behaviors-->

    <!--Services here-->   
   <services>
      <service name="MyWcf.Services.UserService">
        <endpoint address="UserService" behaviorConfiguration="defaultEndpointBehavior"
          binding="webHttpBinding" contract="MyWcf.Services.IUserService" />
      </service>
    </services>

    <!--End of Services-->

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name=""
                          helpEnabled="true"
                          automaticFormatSelectionEnabled="true"
                          defaultOutgoingResponseFormat ="Json"
                          crossDomainScriptAccessEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>


解决方案

I see multiple problems in your code:

405 means method not allowed - it can mean that you are posting data to wrong resource. Are you sure that your address is correct? How do you expose the service? Is it .svc file or ServiceRoute? If it is .svc file the address will be UserService.svc/UserService/ValidateUser

  • UserService.svc because this is entry point for your service (if you are using ServiceRoute you can redefine this
  • UserService because you are defining this relative address in endpoint configuration
  • ValidateUser because that is default entry point for your operation

Now your JSON request is completely bad and your method signature as well. Method signature in your service contract must expect single JSON object = it must be single data contract like:

[DataContract]
public class UserData
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }
}

and operation signature will be:

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
ServiceObject ValidateUser(UserData userData);

There is no wrapper element in JSON request and because of that you must use Bare. Also it is not needed to set response format because you will set it on endpoint level (btw. you must also set request format if you don't).

Once you defined data contract for your request you must correctly define ajax request itself:

$.ajax({
  type: 'POST',
  url: "UserService.svc/UserService/ValidateUser",
  data: '{"UserName":"newuser","Password":"pwd"}',
  contentType: "application/json; charset=utf-8", 
  success: function (msg) {
    alert(msg);
  },

  error: function (xhr, ajaxOptions, thrownError) {
    alert('error');
  }

});

JSON object is as string! and all its members as well!

For last modify your configuration to:

<system.serviceModel>
  <services>
    <service name="UserService.UserService">
      <endpoint address="UserService" kind="webHttpEndpoint" contract="UserService.IUserService" />
    </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  <standardEndpoints>
    <webHttpEndpoint>
      <standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true" />
    </webHttpEndpoint>
  </standardEndpoints>
</system.serviceModel>

If you want to use standardEndpoint you must use kind in endpoint definition and you don't need to specify behavior (it is part of standard endpoint). Also you are not using cross domain calls so you don't need to enable them and you don't need default format because it is resolved automatically.

这篇关于WCF REST服务和jQuery Ajax的帖子:不允许的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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