检测操作是 POST 还是 GET 方法

本文关键字:GET 方法 还是 POST 操作 检测 | 更新日期: 2023-09-27 17:55:25

在MVC 3中,是否可以确定操作是POST还是GET方法的结果?我知道您可以使用[HttpPost]和[HttpGet]装饰操作,以便在发生其中之一时触发特定操作。我想做的是关闭这些属性,并以编程方式确定导致操作的属性。

原因是,由于我的搜索页面的架构方式,我将搜索模型存储在 TempData 中。初始搜索会导致 POST 到搜索结果页面,但寻呼链接都只是指向"/results/2"(对于第 2 页)的链接。他们检查 TempData 以查看模型是否在那里,如果是,请使用它。

当有人使用后退按钮转到搜索表单并重新提交时,这会导致问题。它仍在 TempData 中选取模型,而不是使用新的搜索条件。因此,如果是 POST(即有人刚刚提交了搜索表单),我想先清除 TempData。

检测操作是 POST 还是 GET 方法

HttpRequest对象上的 HttpMethod 属性将为您获取它。您可以只使用:

if (HttpContext.Current.Request.HttpMethod == "POST")
{
    // The action is a POST.
}

或者,您可以直接从当前控制器获取Request对象。这只是一个财产。

最好将其与HttpMethod属性进行比较,而不是字符串。HttpMethod 在以下命名空间中可用:

using System.Net.Http;
if (HttpContext.Request.HttpMethod == HttpMethod.Post.Method)
 {
 // The action is a post
 }

从 .Net Core 3 开始,你可以使用 HttpMethods.Is{Verb} ,像这样:

using Microsoft.AspNetCore.Http
HttpMethods.IsPost(context.Request.Method);
HttpMethods.IsPut(context.Request.Method);
HttpMethods.IsDelete(context.Request.Method);
HttpMethods.IsPatch(context.Request.Method);
HttpMethods.IsGet(context.Request.Method);

您甚至可以更进一步创建自定义扩展,以检查它是读取操作还是写入操作,如下所示:

public static bool IsWriteOperation(this HttpRequest request) =>
    HttpMethods.IsPost(request?.Method) ||
    HttpMethods.IsPut(request?.Method) ||
    HttpMethods.IsPatch(request?.Method) ||
    HttpMethods.IsDelete(request?.Method);

要在 ASP.NET Core 中检测此问题,请执行以下操作:

if (Request.Method == "POST") {
    // The action is a POST
}

如果你像我一样,不喜欢使用字符串文字(使用 DI 的 .net core 2.2 中间件):

public async Task InvokeAsync(HttpContext context)
{
    if (context.Request.Method.Equals(HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
    {
        …
    }
}