问题
Unfortunately, I'm doing some work on a (legacy) project that is build with ASP.NET Web Forms. I can't migrate it to ASP.NET MVC (so please don't suggest that as an answer).
I wish to create an API to expose some of our data. So, I went a head and made a web service. Pretty simple stuff. BUT, for the first few methods, I wish to expose them only as HTTP-GET. For my last method, I wish to expose this only as HTTP-POST.
I'm so used to using ASP.NET MVC, which is why I really love this RESTful way of programming, but I'm not sure how to do this with my web service?
I'm using a URL Rewriter, so that handles the 'RESTfull' consuming of the api (it's lame, but it works).
So, is there a way to block a web service to only accept the HTTP verb?
回答1:
Add the following above the method declaration:
[ScriptMethod(UseHttpGet = false)]
This forces the method to respond only to POST. Set to true if you want the method to respond to GET. The gotcha here is that you need to be using ASP.NET 3.5 or the ASP.NET AJAX Extensions for ASP.NET 2.0. You can read more about this here
回答2:
You can enable GET in the web.config, using:
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
To restrict a single method to POST, you can test HttpContext.Current.Request.HttpMethod at runtime.
回答3:
I'm pretty sure the .net web service class accepts only posted variables.
来源:https://stackoverflow.com/questions/1276098/is-it-possible-to-restrict-certain-asmx-web-service-methods-to-get-or-post-only