我正在发出请求做一个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内容...(除非我为此创建一个类)
我应该怎么做?
答案 0 :(得分: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
用于反序列化内容。
答案 1 :(得分: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
答案 2 :(得分:0)
试试这个。
public string Post(FormDataCollection form) {
string par1 = form.Get("par1");
// ...
}
答案 3 :(得分:0)
我整个上午都在搜索中找到一个既描述了客户端代码又描述了服务器代码的答案,然后终于找到答案了。
简要介绍-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 }
);
答案 4 :(得分:-5)
尝试使用以下方式
[AcceptVerbs("POST")]
[ActionName("myActionName")]
public static void DoSomeStuff(var value)
{
//first way
var x = value;
}