简体   繁体   English

ASP.NET覆盖Web方法

[英]ASP.NET Override a webmethod

I have several WebMethods in a C# ASP.NET web app. 我在C#ASP.NET Web应用程序中有几个WebMethod。 I'd like to change the behavior of all of them to validate each request. 我想更改所有用户的行为以验证每个请求。 Imagine the code below: 想象下面的代码:

[WebMethod]
public static void DoSomething() 
{
    if (ValidateRequest())
    {
        HttpContext.Current.Response.StatusCode = 400;
        // do some other stuff
        return;
    }
    // rest of method
}

I've noticed of course that the ValidateRequest() method call is common to a large portion of my WebMethods. 我当然注意到ValidateRequest()方法调用在我的WebMethods的大部分中是常见的。 Is there anyway I can wire this up so that all WebMethods automatically have this same behavior? 无论如何,我可以将其连接起来,以便所有WebMethod自动具有相同的行为吗? Could I add a second attribute to the method to accomplish this? 我可以在方法中添加第二个属性来完成此操作吗?

Add the validate request in the Begin Request of your Global.asax file. 将验证请求添加到Global.asax文件的“开始请求”中。

Now, you need some sort of code to check if the request should be validated. 现在,您需要某种代码来检查是否应验证请求。

I'm unsure how to do this in webforms... But, what I'd do is: 我不确定如何在网络表单中执行此操作...但是,我要做的是:

use the RequestPath property (and get the method and class name if they match your service URL) 使用RequestPath属性(如果它们与您的服务URL相匹配,则获取方法和类名)

HttpContext.Current.Request.Path;

Then I would create a method attribute and perhaps use reflection to see if the request should be validated. 然后,我将创建一个方法属性,并可能使用反射来查看是否应验证该请求。 (see link below) (请参见下面的链接)

http://msdn.microsoft.com/en-us/library/z919e8tw.aspx http://msdn.microsoft.com/en-us/library/z919e8tw.aspx

This way from this point on you just need to tag your method with your "[Validate]" attribute and it all should just work. 从这一点开始,您只需要使用“ [Validate]”属性标记您的方法,所有这些都应该可以正常工作。

 public class Global : HttpApplication
    {
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
          if(ShouldValidate() && !IsValidRequest()){
              //add your custom error status here perhaps
              Response.StatusCode = 400
              Response.StatusDescription = "Something Bad happened"
              HttpContext.Current.Response.End()
          }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM