简体   繁体   English

参数HTTP Post c#

[英]Arguments HTTP Post c#

I am making an HTTP POST method to get data. 我正在制作一个HTTP POST方法来获取数据。 I have an idea to create a method to get a specific arguments but when I don't have idea to get the arguments taken. 我有一个想法是创建一个方法来获取特定的参数,但是当我不知道获取参数时。 In HTTP GET, arguments are in the URL and is more easy to get the arguments. 在HTTP GET中,参数位于URL中,并且更容易获取参数。 How do I create a method to take all the data in HTTP Post? 如何创建一个方法来获取HTTP Post中的所有数据? In PHP for example when you show the var $_POST you show all data in the body post. 在PHP中,例如当您显示var $ _POST时,您将显示正文帖子中的所有数据。 How can I do this in C#? 我怎么能在C#中做到这一点?

My method is this: 我的方法是这样的:

[HttpPost]
[AllowAnonymous]
public IHttpActionResult Test()
{
// Get URL Args for example is 
var args = Request.RequestUri.Query;
// But if the arguments are in the body i don't have idea.
}

Web API has a feature which automatically binds argument posted to an action inside a controller. Web API具有自动绑定发布到控制器内的操作的参数的功能。 This is called Parameter Binding . 这称为参数绑定 It allows you to simply request the object inside the URL or the body of the POST request, and it does the deserialization magic for you using a thing called Formatters. 它允许您简单地请求URL内部的对象或POST请求的主体,并使用名为Formatters的东西为您执行反序列化魔术。 There is a formatter for XML, JSON, and other known HTTP request types. 有一个XML,JSON和其他已知HTTP请求类型的格式化程序。

For example, lets say I have the following JSON: 例如,假设我有以下JSON:

{
    "SenderName": "David"
    "SenderAge": 35
}

I can create an object which matches my request, we'll call it SenderDetails : 我可以创建一个匹配我的请求的对象,我们称之为SenderDetails

public class SenderDetails
{
    public string SenderName { get; set; }
    public int SenderAge { get; set; }
}

Now, by receiving this object as a parameter in my POST action, I tell WebAPI to attempt to bind that object for me. 现在,通过在POST操作中接收此对象作为参数,我告诉WebAPI尝试为我绑定该对象。 If all goes well, I'll have the information available to me without needing to do any parsing: 如果一切顺利,我将获得可用的信息,而无需进行任何解析:

[Route("api/SenderDetails")]
[HttpPost]
public IHttpActionResult Test(SenderDetails senderDetails)
{
    // Here, we will have those details available, 
    // given that the deserialization succeeded.
    Debug.Writeline(senderDetails.SenderName);
}

If I get you Correctly, in C# you use the [HttpPost] attribute to expose a post method. 如果我正确地告诉你,在C#中你使用[HttpPost]属性来公开post方法。

[HttpPost]
public IHttpActionResult Test()
{
// Get URL Args for example is 
var args = Request.RequestUri.Query;
// But if the arguments are in the body i don't have idea.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM