And*_*rus 13 asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing
ASP.NET MVC4 Web API v1控制器定义如下.它应该接受1或2个查询字符串参数.
但是,如果调用method,则ko参数始终为null.请求如下.如何修复以便klient或namepart参数可以在查询字符串中传递?
Web API v1控制器:
namespace MyApp.Controllers
{
public class CustomersSearchViewModel
{
public string Klient { get; set; }
public string Namepart { get; set; }
}
[Authorize]
public class CustomersController : ApiController
{
public HttpResponseMessage Get(CustomersSearchViewModel ko)
{
// why ko is null ?
var res = GetCustomers(ko.Klient,ko.Namepart);
return Request.CreateResponse(HttpStatusCode.OK,
new { customers = res.ToArray() } );
}
}
}
Run Code Online (Sandbox Code Playgroud)
Controller按请求调用(appl从erp virtal目录运行):
GET /erp/api/customers?namepart=kaks&_=1385320904347 HTTP/1.1
Host: localhost:52216
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
Referer: http://localhost:52216/erp/Sale
Accept-Encoding: gzip,deflate,sdch
Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: .myAuth=8B6B3CFFF3DF64EBEF3D258240D217C56603AF255C869FBB7934560D9F560659342DC4D1EAE6AB28454122A86C3CE6C598FB594E8DC84A; My_Session=5aw2bsjp4i4a5vxtekz
Run Code Online (Sandbox Code Playgroud)
使用默认路由:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
应用程序需要运行win Windows 2003服务器也因此无法使用Web API v.2.
更新
我也试过了
public HttpResponseMessage Get(string klient, string namepart)
Run Code Online (Sandbox Code Playgroud)
但在这种情况下返回404错误,找不到操作.
Réd*_*tar 19
复杂类型是从请求正文中提取的,但您可以更改此默认行为,如下所示:
public HttpResponseMessage Get([FromUri]CustomersSearchViewModel ko)
Run Code Online (Sandbox Code Playgroud)
您的查询字符串应包含名为您的模型属性的参数,否则绑定将不起作用.