14

我正在请求执行 asp.net webapi Post 方法,但我无法获取请求变量。

要求

jQuery.ajax({ url: sURL, type: 'POST', data: {var1:"mytext"}, async: false, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=UTF-8' })
    .done(function (data) {
        ...
    });

WEB API Fnx

    [AcceptVerbs("POST")]
    [ActionName("myActionName")]
    public void DoSomeStuff([FromBody]dynamic value)
    {
        //first way
        var x = value.var1;

        //Second way
        var y = Request("var1");

    }

我无法以两种方式获取 var1 内容...(除非我为此创建一个类)

我该怎么做?

4

5 回答 5

23

第一种方式:

    public void Post([FromBody]dynamic value)
    {
        var x = value.var1.Value; // JToken
    }

请注意,value.Property实际上返回一个JToken实例,因此要获取它的值,您需要调用value.Property.Value.

第二种方式:

    public async Task Post()
    {        
        dynamic obj = await Request.Content.ReadAsAsync<JObject>();
        var y = obj.var1;
    }

以上两种方法都使用 Fiddler。如果第一个选项不适合您,请尝试将内容类型设置为application/json以确保JsonMediaTypeFormatter用于反序列化内容。

于 2012-10-29T20:09:56.757 回答
7

在对此进行了一段时间的思考并尝试了许多不同的事情之后,我最终在 API 服务器上放置了一些断点,并发现请求中塞满了键值对。在我知道它们在哪里之后,很容易访问它们。但是,我只发现此方法适用于 WebClient.UploadString。但是,它确实很容易工作,并允许您加载任意数量的参数,并非常容易地在服务器端访问它们。请注意,我的目标是 .net 4.5。

客户端

// Client request to POST the parameters and capture the response
public string webClientPostQuery(string user, string pass, string controller)
{
    string response = "";

    string parameters = "u=" + user + "&p=" + pass; // Add all parameters here.
    // POST parameters could also easily be passed as a string through the method.

    Uri uri = new Uri("http://localhost:50000/api/" + controller); 
    // This was written to work for many authorized controllers.

    using (WebClient wc = new WebClient())
    {
        try
        {
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            response = wc.UploadString(uri, login);
        }
        catch (WebException myexp)
        { 
           // Do something with this exception.
           // I wrote a specific error handler that runs on the response elsewhere so,
           // I just swallow it, not best practice, but I didn't think of a better way
        }
    }

    return response;
}

服务器端

// In the Controller method which handles the POST request, call this helper:
string someKeyValue = getFormKeyValue("someKey");
// This value can now be used anywhere in the Controller.
// Do note that it could be blank or whitespace.

// This method just gets the first value that matches the key.
// Most key's you are sending only have one value. This checks that assumption.
// More logic could be added to deal with multiple values easily enough.
public string getFormKeyValue(string key)
{
    string[] values;
    string value = "";
    try
    {
        values = HttpContext.Current.Request.Form.GetValues(key);
        if (values.Length >= 1)
            value = values[0];
    }
    catch (Exception exp) { /* do something with this */ }

    return value;
}

有关如何处理多值 Request.Form 键/值对的更多信息,请参阅:

http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.110).aspx

于 2014-05-29T21:25:48.623 回答
2

我整个上午都在寻找一个描述客户端和服务器代码的答案,然后终于弄明白了。

简介 - UI 是一个实现标准视图的 MVC 4.5 项目。服务器端是 MVC 4.5 WebApi。目标是将模型发布为 JSON,然后更新数据库。编写 UI 和后端代码是我的责任。下面是代码。这对我有用。

模型

public class Team
{
    public int Ident { get; set; }
    public string Tricode { get; set; }
    public string TeamName { get; set; }
    public string DisplayName { get; set; }
    public string Division { get; set; }
    public string LogoPath { get; set; }
}

客户端(UI 控制器)

    private string UpdateTeam(Team team)
    {
        dynamic json = JsonConvert.SerializeObject(team);
        string uri = @"http://localhost/MyWebApi/api/PlayerChart/PostUpdateTeam";

        try
        {
            WebRequest request = WebRequest.Create(uri);
            request.Method = "POST";
            request.ContentType = "application/json; charset=utf-8";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            WebResponse response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }
        catch (Exception e)
        {
            msg = e.Message;
        }
    }

服务器端(WebApi 控制器)

    [Route("api/PlayerChart/PostUpdateTeam")]
    [HttpPost]
    public string PostUpdateTeam(HttpRequestMessage context)
    {
        var contentResult = context.Content.ReadAsStringAsync();
        string result = contentResult.Result;
        Team team = JsonConvert.DeserializeObject<Team>(result);

        //(proceed and update database)
    }

WebApiConfig(路由)

        config.Routes.MapHttpRoute(
            name: "PostUpdateTeam",
            routeTemplate: "api/PlayerChart/PostUpdateTeam/{context}",
            defaults: new { context = RouteParameter.Optional }
        );
于 2019-02-08T20:47:16.480 回答
0

试试这个。

public string Post(FormDataCollection form) { 
    string par1 = form.Get("par1");

    // ...
}
于 2017-12-21T03:39:34.723 回答
-5

尝试使用以下方式

[AcceptVerbs("POST")]
[ActionName("myActionName")]
public static void DoSomeStuff(var value)
{
    //first way
   var x = value;
}
于 2012-10-29T11:49:45.067 回答