ASP.NET MVC网页API获取不映射查询字符串强类型参数 [英] ASP.NET MVC Web Api Get Not Mapping QueryString To Strongly Typed Parameter

查看:109
本文介绍了ASP.NET MVC网页API获取不映射查询字符串强类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该参数请求总是空使用Web API。我缺少使用强类型对象作为参数,而不是简单的类型作为参数的东西。

网址

 的http://本地主机:2222 / API / V1 /司EVENTID = 30

控制器动作

 公共虚拟ApiDivisionsResponse获取(ApiDivisionsRequest要求)
        {
            返回_apiDivisionsService.GetDivisions(请求);
        }

对象

 公共类ApiDivisionsRequest:ApiAuthorizedRequest
    {
        公共ApiDivisionsRequest()
        {
            页= 1;
            每页= 10;
        }        公众诠释EVENTID {搞定;组; }
        公众诠释每页{搞定;组; }
        公众诠释页{搞定;组; }
        公共字符串[] {包括获得;组; }
    }


解决方案

我非常强烈地邀请您阅读<一href=\"http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx\">following文章以更好地理解Web API如何参数绑定的作品。看完之后你会明白,在默认情况下的Web API结合查询字符串参数为基本类型和请求正文内容复杂类型。

所以,如果你需要绑定查询字符串参数到复杂的类型,你需要通过与 [FromUri] 参数装饰你的参数可覆盖此默认行为:

 公共虚拟ApiDivisionsResponse获取([FromUri] ApiDivisionsRequest要求)
{
    ...
}

和是的,我同意你的看法 - 这是一个混乱的地狱 - 模型绑定是纯ASP.NET MVC那么容易,他们创建的Web API中的噩梦。但是,它的工作原理,一旦你知道你将避免陷阱。

The parameter request is always null using Web API. Am I missing something with using a strongly typed object as a parameter instead of simple types as the parameters.

Url

http://localhost:2222/api/v1/divisions?EventId=30

Controller Action

public virtual ApiDivisionsResponse Get(ApiDivisionsRequest request)
        {
            return _apiDivisionsService.GetDivisions(request);
        }

Object

public class ApiDivisionsRequest : ApiAuthorizedRequest
    {
        public ApiDivisionsRequest()
        {
            Page = 1;
            PageSize = 10;
        }

        public int EventId { get; set; }
        public int PageSize { get; set; }
        public int Page { get; set; }
        public string[] Includes { get; set; }
    }  

解决方案

I very strongly invite you to read the following article to better understand how parameter binding works in the Web API. After reading it you will understand that by default the Web API binds query string parameters to primitive types and request body content to complex types.

So if you need to bind query string parameters to complex types you will need to override this default behavior by decorating your parameter with the [FromUri] parameter:

public virtual ApiDivisionsResponse  Get([FromUri] ApiDivisionsRequest request)
{
    ...
}

And yeah, I agree with you - that's a hell of a mess - model binding was so easy in plain ASP.NET MVC and they created a nightmare in the Web API. But once you know how it works you will avoid the gotchas.

这篇关于ASP.NET MVC网页API获取不映射查询字符串强类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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