【发布时间】:2018-07-07 04:29:56
【问题描述】:
收到在控制器中找不到 http 资源或操作的错误消息。在 web api 中,我有一个 from body 和 from uri 参数。
[HttpPost]
public IHttpActionResult processfields(
[FromUri]string field1,
[FromUri]string field2,
[FromBody] string field3,
[FromUri]string field4
){...}
在客户端我想通过做来调用 web api--
using (var client = new HttpClient())
{
//set up client
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var values = new Dictionary<string, string>();
values.Add("field1", field1);
values.Add("field2", field2);
values.Add("field3", field3);
values.Add("field4", filed4);
var jsonString = JsonConvert.SerializeObject(values);
try
{
HttpResponseMessage Res = client.PostAsync("api/home/processfields", new StringContent(jsonString, Encoding.UTF8, "application/json")).Result;
var result = Res.Content.ReadAsStringAsync();
}
}
在调试时,它执行上面的最后一行,但没有任何反应,并且错误消息显示--
{"Message":"未找到与请求 URI 'http://xxx.xxx.xx.xx:1234/api/home/processfields'匹配的 HTTP 资源。","MessageDetail":"未在控制器 'home' 上找到与请求匹配的操作。"}
我的 webapi.config 有
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
【问题讨论】:
-
您正在发送请求正文中的所有内容,而操作已配置为期望来自 URI 的参数。
标签: c# .net asp.net-web-api dotnet-httpclient asp.net-web-api-routing