Skip to main content
 首页 » 编程设计

c#之ASP.NET 覆盖 web 方法

2024年01月01日36傻小

我在 C# ASP.NET Web 应用程序中有几个 WebMethods。我想改变他们所有人的行为来验证每个请求。想象一下下面的代码:

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

当然,我注意到 ValidateRequest() 方法调用对于我的大部分 WebMethods 来说是通用的。无论如何我可以连接它以便所有 WebMethods 自动具有相同的行为吗?我可以向该方法添加第二个属性来完成此操作吗?

请您参考如下方法:

在 Global.asax 文件的开始请求中添加验证请求。

现在,您需要某种代码来检查请求是否应该被验证。

我不确定如何在网络表单中执行此操作...但是,我会做的是:

使用 RequestPath 属性(如果它们与您的服务 URL 匹配,则获取方法和类名)

HttpContext.Current.Request.Path; 

然后我会创建一个方法属性并可能使用反射来查看请求是否应该被验证。 (见下面的链接)

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

从现在开始,您只需要用“[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() 
          } 
        }