How to force web API to recognise querystring para

2020-07-02 14:22发布

ASP.NET MVC4 Web API v1 controller is defined below. It should accept 1 or 2 query string parametrs.

However ko parameter is always null if method is called. Request is below. How to fix so that klient or namepart parameter can passed in query string ?

Web API v1 controller:

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() } );
            }

        }
    }

Controller is invoked by request (appl is running from erp virtal directory):

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

default routing is used:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

Application needs to be run win Windows 2003 server also so Web API v.2 cannot used.

Update

I tried also

public HttpResponseMessage Get(string klient, string namepart)

but in this case 404 error is returned, action is not found.

2条回答
够拽才男人
2楼-- · 2020-07-02 14:54

Another option is to implement a custom type provider. This allows control over the representation in the query string, and means you don't have to add the [FromUri] attribute to your action methods. This makes sense if you have widespread reuse of a complex parameter type, or need a custom representation.

A good example of this is given in this blog post where a location with latitude and longitude is implemented using both techniques.

查看更多
劳资没心,怎么记你
3楼-- · 2020-07-02 15:00

Complex types are fetched from the body of a request, but you can change this default behaviour like this :

public HttpResponseMessage Get([FromUri]CustomersSearchViewModel ko)

Your querystring should contain parameters named like your model properties, otherwise the binding won't work.

查看更多
登录 后发表回答