【问题标题】:WCF service Post request gives error if calling from browser like "Method not allowed."如果从浏览器调用“不允许方法”,WCF 服务发布请求会出错。
【发布时间】:2015-09-05 05:18:11
【问题描述】:

我已经创建了 WCF POST 方法。当我通过在查询字符串中传递参数从浏览器调用它时,它给了我类似的错误

方法不允许。请参阅服务帮助页面以构建对服务的有效请求

我的代码在界面中

[ServiceContract]
public interface IService
{
    //[OperationContract]
    //[WebGet(UriTemplate = "/UpdateDeviceStatus?FaultStatus={FaultStatus}&MacAddress={MacAddress}", RequestFormat = WebMessageFormat.Xml)]
    //string UpdateDeviceStatus(string FaultStatus, string MacAddress);


    [OperationContract]
    [WebInvoke(Method = "POST",
    BodyStyle = WebMessageBodyStyle.WrappedRequest,
    ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
    UriTemplate = "/UpdateDeviceStatus?FaultStatus={FaultStatus}&MacAddress={MacAddress}")]
    [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    string UpdateDeviceStatus(string FaultStatus, string MacAddress);
}

在 Service.svc 中

public string UpdateDeviceStatus(string FaultStatus, string MacAddress)
{
    try
    {
       // here my operation
    }
    catch (Exception ex)
    {
        return "Failed to update";
    }
}

我从浏览器调用的 URL 是

http://localhost:2121/WcfService/Service.svc/UpdateDeviceStatus?FaultStatus={1}&MacAddress={20:10:00:20:10:00}

注意:如果我使用 webGet 方法,那么它可以工作,但对于 POST 方法它不起作用,任何人都可以给我解决方案吗?

【问题讨论】:

  • 浏览器无法发送POST请求。

标签: asp.net wcf asp.net-mvc-4 wcf-data-services


【解决方案1】:

通过在浏览器中输入地址来访问资源时,请求是通过 GET 完成的。

这就是您的服务抱怨的原因:请求是通过 GET 完成的,这是不允许的,因为您定义为仅允许 POST 请求 ([WebInvoke(Method = "POST",)。

为了能够执行 GET 以外的其他请求,我建议您使用像 Postman 这样的工具,它允许您编写任何类型的 http 请求。

您通过错误消息获得的提示也非常有价值:查看您的服务帮助页面。所需的格式和生成的输出显示在那里。如需启用服务帮助页面,请查看this article

【讨论】:

    【解决方案2】:

    试试看——

    public class CompositeType
    {
        public string FaultStatus { get; set; }
        public string MacAddress { get; set; }
    }
    
    
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "post")]
    CompositeType GetDataUsingDataContract(CompositeType composite);
    

    使用Fiddler 或类似工具来检查它是否有效。

    此外,您可以修改您的 config 以启用对您的服务的帮助 -

     <endpointBehaviors>
        <behavior name="e">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    

    这可以通过导航到 yoururl/service.svc/help

    帮助您处理允许的操作、可能的请求和响应正文格式等

    【讨论】:

      【解决方案3】:

      使用浏览器的调试工具(开发者选项)(对于 Firefox,它是 F12 键)。 在网络选项卡中,您会发现浏览器正在向服务器发送 get 请求,而服务器正在等待 POST。 因此错误。

      【讨论】:

        猜你喜欢
        • 2017-03-17
        • 2017-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        相关资源
        最近更新 更多