如何强制控制器/动作使用JsonValueProvider [英] How to force controller/action to use JsonValueProvider

查看:103
本文介绍了如何强制控制器/动作使用JsonValueProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!

我使用ASP.NET MVC 3,其中<一个href=\"http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx\"相对=nofollow> JsonValueProvider 是内置。

I'm using ASP.NET MVC 3 where JsonValueProvider is built-in.

问题是,它只有在内容类型:应用程序/ JSON 指定

我建立了一个API,其中JSON是唯一支持的格式,我不希望强制客户端设置此头。

I'm building an API where JSON is the only supported format and I don't want to force clients setting this header.

有没有办法强制控制器/动作使用特定ValueProvider?

Is there any way to force controller/action to use particular ValueProvider?

推荐答案

虽然这个作品,是非常简单的,似乎更一个黑客攻击。你可以做的是创建 AuthorizeAttribute 派生的属性,并在 OnAuthorization 您设置的内容类型为application / JSON

Although this works and is very simple, it seems more of a hack. What you can do is create an attribute deriving from AuthorizeAttribute and in OnAuthorization you set the Content-Type to application/json.

public class JsonActionAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.HttpContext.Request.ContentType = "application/json";
    }
}

[JsonAction]
public ActionResult JsonOnlyAction(string var1, int var2, ...)
{
    ...
}

此属性也可以在控制器级应用。

This attribute can also be applied at the controller level.

本来我尝试设置内容类型在一个动作过滤器,但问题是 OnActionExecuting 出现的之后的价值供应商进行选择,设置内容型有为时已晚。

Originally I tried setting the Content-Type in an action filter but the problem is OnActionExecuting occurs after value providers are selected so setting the content-type there is too late.

OnAuthorization 出现的的价值提供者选择,因为 JsonValueProviderFactory 检查 Request.ContentType.StartsWith(应用/ JSON)这将确保它的选择。

OnAuthorization occurs before value providers are selected, and since the JsonValueProviderFactory checks for Request.ContentType.StartsWith("application/json") this will ensure it's selected.

这篇关于如何强制控制器/动作使用JsonValueProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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