【问题标题】:Global.asax.cs Application_BeginRequest - Throw WebFaultExceptionGlobal.asax.cs Application_BeginRequest - 抛出 WebFaultException
【发布时间】:2022-02-07 16:48:33
【问题描述】:

WCF 中有没有一种方法可以根据接收到的请求类型检查某些逻辑?这可以在实际的服务端点代码中完成吗?

例如:

服务初始化后,我的服务收到一个 PUT 请求。在 myService.svc.cs 中,我希望有如下所示的逻辑:

if httpRequest.Type == PUT
{
    //Do Something
} 

这可能吗?我确信有比为每个 PUT 类型的操作合同添加逻辑更好的方法来处理请求。抱歉,如果这个问题没有意义,我对 WCF 有点陌生,并且正在努力学习。如果您需要澄清剂,请告诉我。

编辑:

这是 myService.svc.cs 当前的样子:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public partial class MyService: IMyService
{
    public async Task<someObject> GetMethod1 () // Some GET Method
    { 
        doSomethingForGetRequests();
        //method implementation
    }

    public async Task<someObject> GetMethod2 () // Some GET Method
    { 
        doSomethingForGetRequests();
        //method implementation
    }

    public async Task<someObject> PutMethod1 () // Some PUTMethod
    { 
        doSomethingForPutRequests();
        //method implementation
    }

    doSomethingForPutRequests()
    {
       if(config.IsReadOnly)
       {
           throw new WebFaultException(HttpStatusCode.BadRequest);
       }
    }
}


我想知道是否有一个地方可以在请求到达这些方法之前将 doSomethingForGetRequest() 和 doSomethingForPutRequest() 放置在中心位置,这样我就不必将这些方法添加到我的每个服务方法中。

global.asax.cs Application_BeginRequest() 是否适合这个逻辑?

【问题讨论】:

  • 您可以使用指定请求类型的属性来装饰您的方法。这个问题中给出的例子有帮助吗?:stackoverflow.com/questions/4197956/…
  • 所以知道 HTTP 方法已经在我的界面中定义了。我的具体问题是是否有一个中心位置可以根据请求类型添加逻辑?我对上面进行了编辑,看看这是否更清楚我想要做什么......
  • 下面蓝黄的回答似乎有道理。你可以试试这个:if (HttpContext.Current.Request.HttpMethod == "POST")

标签: c# .net rest wcf


【解决方案1】:

也许消息检查器可以帮助您,它会在到达服务的每个请求上调用。

IDispatchMessageInspector 定义了在服务应用程序中启用自定义检查或修改入站和出站应用程序消息的方法。

您可以查看以下帖子:
Detect if action is a POST or GET method
Call the method automatically for each and every request in the WCF REST

【讨论】:

  • +1 您可能希望在答案中直接包含一些代码。如果链接在某个时候消失,这将使答案与 OP 更相关,同时还能保持其有用性。
猜你喜欢
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2020-10-21
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多