开发者

How do you access a WebMethod in class library?

开发者 https://www.devze.com 2023-01-10 20:57 出处:网络
I have a custom class library that performs validation. I want to open up this class for use within Javascript. I understand that I can easily achieve this by utilizing WebServices/WCF or by crea开发者

I have a custom class library that performs validation. I want to open up this class for use within Javascript. I understand that I can easily achieve this by utilizing WebServices/WCF or by crea开发者_Python百科ting a function on my page with the WebMethod attribute, but it'd be nice not to have to set all that up for every project.

Ideally I'd like to just add the WebMethod attribute to my class library methods and then call them using Javascript.


Unfortunately, you will have to expose an endpoint that your Javascript function can see. In ASP.NET this is most easily done with the web method attribute that you have encountered. However, this method requires two parts the endpoint and the actual code. If you think about it, it makes sense. Javascript has no way of talking directly to a compiled .NET assembly. It must go through a type agnostic interface. One thing that you can do, and you may be doing this, is generate the .asmx file with the web method and then have that call your class library method. This will not prevent you from having the .asmx endpoint, but will prevent any duplication of the actual code. I don't have a lot of experience with WCF, but I believe that you will still need an endpoint of some sort to interface between Javascript and C#.


The WebMethod attribute has to be used from a page level method. It's not too much of a hassle though if you set your library up correctly. A WebMethod is just a static method, but if you plan to use it in multiple pages, then you most definately want to make it a WCF service. Neither of these should be difficult and the overhead is minimal.

Alternatively you could use a base Page class that all your other pages inherit from and define your WebMethod there. This class could live in class library somewhere and be used across multiple projects.

0

精彩评论

暂无评论...
验证码 换一张
取 消