c# - ASP.NET 覆盖 web 方法

标签 c# asp.net webmethod

我在 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()
          }
        }

关于c# - ASP.NET 覆盖 web 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11594412/

相关文章:

c# - 从字符串中删除嵌入式 ASCII 控制字符

c# - Linq to SQL 背后的安全性

asp.net - ASP.NET 中可用的 Owin/Katana 缺少什么?

c# - 如何在 asp.net 的 WebMethod 中使用 ScriptManager.RegisterStartupScript?

c# - 如何在Asp.net C#中调用webmethod

C# 允许同时控制台输入和输出

c# - 小于或等于日期不应允许输入

C# 文本格式 - 对齐无法正常工作

c# - 以 JSON 格式返回文件数据

javascript - JSON 和 ASP.NET WebMethod 不触发服务器端方法