什么是ASP.NET MVC中的WebApi [FromUri]等效项? [英] What's the WebApi [FromUri] equivalent in ASP.NET MVC?

查看:122
本文介绍了什么是ASP.NET MVC中的WebApi [FromUri]等效项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WebApi中,我可以使用[FromUri]装饰控制器动作上的参数,以使URI的成分反序列化"(如果需要的话)成为POCO模型. aka模型绑定.

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; aka model-binding.

尽管从2.0版本开始使用MVC,但我从未在网站上使用过它(不知道为什么).在ASP.NET MVC 5中相当于什么?

Despite using MVC since 2.0, I've never used it for websites (dunno why). What's the equivalent of it in ASP.NET MVC 5?

除非我需要引用库,否则似乎无法在IDE中识别该属性.

The attribute doesn't seem to be recognised in the IDE unless I need to reference a library.

我希望~/thing/2014/9绑定到以下模型:

I'd like ~/thing/2014/9 to bind to the model below:

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

谢谢

更新

在另一个问题(上面的链接)中,OP表示:

In the other question (link above), the OP says:

但是,将其切换为普通的MVC而不是WebApi,并且默认的模型绑定程序会崩溃,并且无法绑定嵌套数组中对象的属性

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

这暗示他正在使用WebApi中的属性.我猜.我没有这些引用,因为我在MVC中,所以(ab)使用WebApi的版本是在MVC中实现此目的的公认方法吗?

Which implies that he's using the attribute from the 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?

更新2

该问题的答案是:

您需要根据MVC模型联编程序命名约定构造查询字符串.

You need to construct your query string respecting MVC model binder naming conventions.

[FromUri]属性被完全忽略,因为MVC DefaultModelBinder不知道该属性

Additionally [FromUri] attribute in your example action is completely ignored, since it's not known to MVC DefaultModelBinder

因此,如果他在错误的属性方面获得了一些成功,那么我仍然不知道OP在这个问题上甚至在谈论什么.

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.

我想我希望得到一个明确的答案,而不是其他问题的泥泞.

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

至少在使用URL /thing?Year=2014&Month=9时.

At least, when using the URL /thing?Year=2014&Month=9.

问题在于您的路由. URL /thing/2014/9不会使用MVC的默认路由进行映射,因为它是/{controller}/{action}/{id},其中{id}是可选的int.

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.

最简单的方法是使用属性路由:

The easiest would be to use attribute routing:

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

这会将URL映射到您的模型.

This will map the URL to your model.

这篇关于什么是ASP.NET MVC中的WebApi [FromUri]等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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