如何使用asp.net webapi获取Json Post值

15

我正在发起一个请求,使用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的内容...

我该怎么做呢?

5个回答

24

第一种方法:

    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来反序列化内容。


1
如果你想在一个帮助方法中实现这个功能,但并不完全理解 await 语法,你可以使用 Request.Content.ReadAsAsync<JObject>().Result["var1"](参见完整答案)。 - drzaus

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/zh-cn/library/6c3yckfw(v=vs.110).aspx


2

我整个上午都在寻找一篇涵盖客户端和服务器端代码的答案,最终我终于找到了。

简单介绍-UI是一个实现了标准视图的MVC 4.5项目。服务器端是一个MVC 4.5 WebApi。目标是将模型作为JSON进行POST,并随后更新数据库。我的责任是编写UI和后端代码。以下是代码。这对我很有效。

模型

Original Answer翻译成"最初的回答"

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; }
}

客户端(用户界面控制器)

    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 }
        );

0

试试这个。

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

    // ...
}

-5
尝试使用以下方法
[AcceptVerbs("POST")]
[ActionName("myActionName")]
public static void DoSomeStuff(var value)
{
    //first way
   var x = value;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接