我正在使用 Asp.NET WebApi,让我感到困惑的一件事是完成请求时的绑定(bind)。
我有这个 ViewModel:
[DataContract(Name="Store")]
public class StoreDm
{
[DataMember(IsRequired = true)]
[MinLength(3)]
public string Name { get; set; }
[DataMember(IsRequired = true)]
public double Latitude { get; set; }
[DataMember(IsRequired = true)]
public double Longitude { get; set; }
}
public HttpResponseMessage GetStoreNames(StoreDm vm)
{
if (ModelState.IsValid)
{
}
}
RestClient c = new RestClient("http://localhost:3333/api/store");
RestRequest r = new RestRequest("/GetStoreNames", Method.GET);
r.AddParameter("Name", autoComplete);
r.AddParameter("Latitude", "4");
r.AddParameter("Longitude", "-7");
var d = c.BuildUri(r);
c.ExecuteAsync(r, response2 =>
{
var content = response2.Content;
});
我的 StoreDm 为空。
我没有在这么多层面上理解这一点。首先,无论出于何种原因,ModelState 认为“空”ViewModel 是有效的,我都在我的所有属性上设置了 IsRequired。
其次,我不明白为什么它是 null
。我必须添加 [FromUri]
才能绑定(bind)它。如果这是一个 Post
并且具有相同的 restClient 代码,但也有人正在使用 fiddler body 请求,会发生什么情况。
如果我被迫输入 [FromUri]
那么我认为 fiddler body 请求不会起作用。
我怎样才能让两个请求都通过并正确绑定(bind)?
最佳答案
Web API 参数绑定(bind)(摘自此处:Routing and Action Selection)执行以下操作:
参数绑定(bind)。参数绑定(bind)是 Web API 为参数创建值的方式。这是参数绑定(bind)的默认规则:
- 简单类型取自 URI。
- 复杂类型取自请求正文。
因此,默认情况下,任何复杂类型(如 StoreDm
类)都应成为主体的一部分
如标准定义超文本传输协议(protocol)所述4.3 Message Body
The rules for when a message-body is allowed in a message differ for requests and responses.
The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.
因此,虽然 Web API 提供了一些通用功能,但它力求通用。可能有带或不带消息正文的请求。因此,有了这个,操作选择和参数绑定(bind)是常见的,无需推断“当前”请求特定的,并且可能是明显的设置 (我们认为,GET 将始终具有所有参数(StoreDm 的属性
对象)在 URI 中......但引擎没有)
POST 将开箱即用地绑定(bind) StoreDm
,因为它的属性将在正文中找到,这是复杂对象的标准绑定(bind)。
GET打破了规则,(复杂类型的)属性在URI中,所以我们只需要通知框架:[FromUri]。在其他情况下,将找到方法,将传递 null(从消息体绑定(bind))
关于c# - 为什么我必须指定 [FromUri] 才能让它工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16927862/