簡體   English   中英

檢測動作是 POST 還是 GET 方法

[英]Detect if action is a POST or GET method

在 MVC 3 中,是否可以確定操作是 POST 還是 GET 方法的結果? 我知道您可以使用 [HttpPost] 和 [HttpGet] 來裝飾這些動作,以在其中一個發生時觸發特定的動作。 我想做的是關閉這些屬性並以編程方式確定哪個屬性導致了操作。

原因是,由於我的搜索頁面的架構方式,我將搜索模型存儲在 TempData 中。 初始搜索導致對搜索結果頁面的 POST,但分頁鏈接都只是指向“/results/2”(第 2 頁)的鏈接。 他們檢查 TempData 以查看模型是否在其中,如果存在則使用它。

當有人使用后退按鈕轉到搜索表單並重新提交時,這會導致問題。 它仍然在 TempData 中選擇模型,而不是使用新的搜索條件。 因此,如果是 POST(即某人剛剛提交了搜索表單),我想先清除 TempData。

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
 }

要在 ASP.NET Core 中檢測到這一點:

if (Request.Method == "POST") {
    // 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);

如果您像我一樣不喜歡使用字符串文字(使用 DI 的 .net core 2.2 中間件):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM