【问题标题】:ASP.NET Web service - restrict methods to HttpGet or HttpPostASP.NET Web 服务 - 将方法限制为 HttpGet 或 HttpPost
【发布时间】:2012-10-28 10:32:10
【问题描述】:

我正在尝试创建一个以不同方式响应 HttpGet 和 HttpPost 请求的 Web 服务。

我已经用这个启用了 HttpGet:

<webServices>
  <protocols>
    <add name="HttpGet"/>
  </protocols>
</webServices>

我创建了 2 个函数,一个应该为 HttpPost 请求触发,另一个 - 在 HttpGet 上:

[WebMethod]
[HttpPost]
[ActionName("HelloWorld")]
public string HelloWorldPost()
{
    return "Hello POST World";
}

[WebMethod]
[HttpGet]
public string HelloWorld()
{
    return "Hello GET World";
}

但是,HttpGet、HttpPost 和 ActionName 似乎被完全忽略了。所有对 HelloWorld 的请求(post 或 get)都会触发第二个函数。我需要以其他方式执行此操作吗?我也尝试用这个来限制功能:

[ScriptMethod(UseHttpGet = false)]

但这也没什么区别。

【问题讨论】:

  • 你在使用asp.net webapi吗?
  • 我猜不是...我正在使用 Visual Studio(.NET 框架 3.5)中的“ASP.NET Web 服务应用程序”项目类型。我没有下载任何额外的库或 API。
  • HttpPostAttribute 来自 MVC,仅存在于 .NET 4.0 msdn.microsoft.com/en-us/library/…
  • 您使用的是古老的 ASMX 技术,不应该用于新的开发。

标签: asp.net web-services http-post asmx http-get


【解决方案1】:

我有个主意。

对于初学者,您的网络服务的 web.config 文件将如下所示:

<webServices>
  <protocols>
     <add name="HttpGet"/>
     <add name="HttpPost"/>
  </protocols>
</webServices>

接下来,不管你使用什么表单方法,你都调用了一个web方法x。

[WebMethod]
public string X()
{
  //so, you detect which method is invoked by using 
  // HttpContext.Current.Request.HttpMethod
  if (HttpContext.Current.Request.HttpMethod == "POST") {
    //do something now you know it is post method
  }
  else {
    //now, it should be get method and you do something different
  }
//end of web method
}

我的主要观点是您检查HttpContext.Current.Request.HttpMethod 并根据使用的方法调用不同的方法。

【讨论】:

    【解决方案2】:

    ASP.NET Web 服务应用程序的行为与 ASP.NET MVC 不同,这符合您的预期。如 Amiram Korach 所述,在您的代码中,HttpGet/HttpPost 和 ActionName 属性都属于 MVC。当托管为 Web 服务应用程序时,这些属性将被忽略。

    Web 服务应用程序中的“路由”基于方法名称(HelloWorldPost 和 HelloWorld),而不是基于 HTTP VERB。

    要触发 POST 流程,您必须调用 HelloWorldPost (service.asmx/HelloWorldPost)

    【讨论】:

    • 谢谢。你几乎证实了我的怀疑——我混淆了两种不同的东西。我使用 WCF 服务重写了整个内容,它现在对我来说可以正常工作:)
    猜你喜欢
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2021-07-29
    • 2011-10-04
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多