I have an action defined in a WebAPI2 controller as follows:
我在WebAPI2控制器中定义了一个操作,如下所示:
[HttpPost]
[Route("DataImport/Product/")]
public DataImportJournalEntry ImportData([FromBody] string base64)
{
return _dataImportService.Import(Convert.FromBase64String(base64));
}
and I'm building a request, using RestSharp, as follows:
我正在使用RestSharp构建一个请求,如下所示:
var base64 = {4Kb xml file loaded and encoded to base64}
var client = new RestClient(Config.BaseAddress);
var request = new RestRequest("DataImport/Product/", Method.POST);
request.AddParameter("base64", base64, ParameterType.GetOrPost);
request.AddHeader("accepts", "application/json");
var response = client.Execute<DataImportJournalEntry>(request);
The routing is correct as the action is called but the base64 parameter is null on the server side?
调用操作时路由是正确的,但服务器端的base64参数为null?
1 个解决方案
#1
Found it..when using the FromBody
attribute there can be only one parameter in the body and WebAPI is looking for it as ={value} not as you would expect {key}={value}. So I simply passed the parameter name as an empty string in the test:
找到它..当使用FromBody属性时,正文中只能有一个参数,而WebAPI正在查找= {value}而不是您所期望的{key} = {value}。所以我只是在测试中将参数名称作为空字符串传递:
...
var request = new RestRequest("DataImport/Product/", Method.POST);
request.AddParameter("", base64);
...
More details here: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
更多细节:http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
#1
Found it..when using the FromBody
attribute there can be only one parameter in the body and WebAPI is looking for it as ={value} not as you would expect {key}={value}. So I simply passed the parameter name as an empty string in the test:
找到它..当使用FromBody属性时,正文中只能有一个参数,而WebAPI正在查找= {value}而不是您所期望的{key} = {value}。所以我只是在测试中将参数名称作为空字符串传递:
...
var request = new RestRequest("DataImport/Product/", Method.POST);
request.AddParameter("", base64);
...
More details here: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
更多细节:http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/