检测操作是POST还是GET方法

Sco*_*ott 40 c# asp.net-mvc

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

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

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

Joh*_*soe 79

HttpMethod该物业HttpRequest的对象会得到它.你可以使用:

if (HttpContext.Current.Request.HttpMethod == "POST")
{
    // The action is a POST.
}
Run Code Online (Sandbox Code Playgroud)

或者您可以Request直接从当前控制器获取对象.这只是一个属性.

  • 如果需要常量,可以使用System.Net.WebRequestMethods.Http集合. (5认同)

Fac*_*cca 14

从 .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);
Run Code Online (Sandbox Code Playgroud)

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

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


Ans*_*lal 7

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

using System.Net.Http;

if (HttpContext.Request.HttpMethod == HttpMethod.Post.Method)
 {
 // The action is a post
 }
Run Code Online (Sandbox Code Playgroud)


All*_*ice 7

要在 ASP.NET Core 中检测到这一点:

if (Request.Method == "POST") {
    // The action is a POST
}
Run Code Online (Sandbox Code Playgroud)