如何强制网络API来识别查询参数 [英] How to force web API to recognise querystring parameter

查看:169
本文介绍了如何强制网络API来识别查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET MVC4网络API v1的控制器被定义如下。它应接受1或2的查询字符串parametrs。

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

不过高参数总是空,如果方法被调用。要求如下。
如何解决这样klient或namepart参数可以在查询字符串中传递?

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 ?

网页API V1控制器:

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

        }
    }

控制器被要求调用(APPL从ERP virtal目录下运行):

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

应用程序需要运行赢在Windows 2003服务器也因此无法使用的Web API第2版。

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

更新

我也试过

public HttpResponseMessage Get(string klient, string namepart)

但在这种情况下,返回404错误,没有发现动作

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

推荐答案

复杂类型是从请求的主体牵强,但你可以改变这样的默认行为:

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.

这篇关于如何强制网络API来识别查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆