使用字符串参数调用Web API [英] call to web api with string parameter
问题描述
我有一个Web api,其中有2种方法,一种没有参数,两种具有不同类型的参数(字符串和整数).当调用字符串方法时,它不起作用...我在这里想念什么?
I have a web api where I have 2 methods, one without parameter and two with different types of parameter (string and int). When calling the string method it doesnt work...what am I missing here?
public class MyControllerController : ApiController
{
public IHttpActionResult GetInt(int id)
{
return Ok(1);
}
public IHttpActionResult GetString(string test)
{
return Ok("it worked");
}
}
WebApiConfig.cs:
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
我的电话:
/api/MyController/MyString//不工作
/api/MyController/MyString //Doesnt work
/api/MyController/1//工作
/api/MyController/1 //work
我收到以下错误:
参数字典在'TestAngular.Controllers.MyControllerController'中的方法'System.Web.Http.IHttpActionResult GetInt(Int32)'中包含非空类型'System.Int32'的参数'id'的空条目.可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetInt(Int32)' in 'TestAngular.Controllers.MyControllerController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
我的请求中缺少什么?
推荐答案
您必须更改您的uri的
You have to change your uri's
/api/MyController
/api/MyController/string
/api/MyController/1
您不必指定方法.
You could take look at this tutorial on asp.net for further clarification.
这篇关于使用字符串参数调用Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!