简体   繁体   English

什么是 ASP.NET MVC 中的 WebApi [FromUri] 等价物?

[英]What's the WebApi [FromUri] equivalent in ASP.NET MVC?

In WebApi I can decorate a parameter on a controller action with [FromUri] to have the components of the URI 'deserialized', if you will, into a POCO model;在 WebApi 中,我可以使用[FromUri]装饰控制器操作上的参数,以将 URI 的组件“反序列化”,如果您愿意,可以将其转换为 POCO 模型; aka model-binding.又名模型绑定。

Despite using MVC since 2.0, I've never used it for websites (I don't know why).尽管从 2.0 开始使用 MVC,但我从未将它用于网站(我不知道为什么)。 What's the equivalent of it in ASP.NET MVC 5?它在 ASP.NET MVC 5 中的等价物是什么?

The attribute doesn't seem to be recognised in the IDE unless I need to reference a library. IDE 中似乎无法识别该属性,除非我需要引用库。

I'd like ~/thing/2014/9 to bind to the model below:我希望~/thing/2014/9绑定到下面的模型:

public class WhateverModel
{
    public int Year { get; set; }
    public int Month { get; set; }
}

Thanks谢谢

Update更新

In the other question (link above), the OP says:在另一个问题(上面的链接)中,OP 说:

However, switch this to plain MVC not WebApi and the default model binder breaks down and cannot bind the properties on objects in the nested array但是,将其切换为普通 MVC 而不是 WebApi,并且默认模型绑定器会崩溃,无法绑定嵌套数组中对象的属性

Which implies that he's using the attribute from the WebApi.这意味着他正在使用来自 WebApi 的属性。 I guess.我猜。 I don't have those references, because I'm in MVC, so is (ab)using WebApi's version the accepted way to do this in MVC?我没有这些参考资料,因为我在 MVC 中,所以(ab)使用 WebApi 的版本是在 MVC 中执行此操作的公认方式吗?

Update 2更新 2

In the answer to that question is:这个问题的答案是:

You need to construct your query string respecting MVC model binder naming conventions.您需要构建符合 MVC 模型绑定器命名约定的查询字符串。

Additionally [FromUri] attribute in your example action is completely ignored, since it's not known to MVC DefaultModelBinder此外,您的示例操作中的[FromUri]属性被完全忽略,因为 MVC DefaultModelBinder 不知道它

So I'm still left not knowing what to do or what on Earth the OP was even talking about in that question, if he was getting some success with the wrong attribute.所以我仍然不知道该怎么做,或者 OP 在这个问题上到底在谈论什么,如果他用错误的属性获得了一些成功。

I guess I'm hoping for a clear answer and not the mud of that other question.我想我希望得到一个明确的答案,而不是其他问题的泥泞。

It'll Just Work™:它会起作用™:

[HttpGet]
public ActionResult Thing(WhateverModel model)
{
    // use model
    return View();
}

At least, when using the URL /thing?Year=2014&Month=9 .至少,当使用 URL /thing?Year=2014&Month=9

The problem is your routing.问题是你的路由。 The URL /thing/2014/9 won't map using MVC's default route, as that is /{controller}/{action}/{id} , where {id} is an optional int . URL /thing/2014/9不会使用 MVC 的默认路由映射,因为它是/{controller}/{action}/{id} ,其中{id}是可选的int

The easiest would be to use attribute routing:最简单的方法是使用属性路由:

[HttpGet]
[Route("/thing/{Year}/{Month}"]
public ActionResult Thing(WhateverModel model)
{
    // use model
    return View();
}

This will map the URL to your model.这会将 URL 映射到您的模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM