随着MVC3,我怎么可以改变的基础上的&QUOT控制器/动作;同意]头? [英] With MVC3, how can I change the controller/action based on the "accept" header?

查看:215
本文介绍了随着MVC3,我怎么可以改变的基础上的&QUOT控制器/动作;同意]头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要作为一个应用程序包罗万象的,可以从各种目标是未来的请求。我希望能够重定向到我的应用程序基础上,接受头的值不同的控制器/动作。

I have an application that is going to act as a "catch-all" for requests that could be coming from a variety of targets. I would like to be able to redirect to a different controller/action in my application based on the value of the "accept" header.

澄清:我想如果可能的话要做到这一点没有一个HTTP处理程序,

Clarification: I would like to do this without an HTTP Handler, if possible.

推荐答案

您可以编写一个定制路线:

You could write a custom route:

public class MyRoute : Route
{
    public MyRoute(string url, object defaults)
        : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
    {

    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }

        var accept = httpContext.Request.Headers["Accept"];
        if (string.Equals("xml", accept, StringComparison.OrdinalIgnoreCase))
        {
            rd.Values["action"] = "xml";
        }
        else if (string.Equals("json", accept, StringComparison.OrdinalIgnoreCase))
        {
            rd.Values["action"] = "json";
        }
        return rd;
    }
}

,然后注册此路线:

and then register this route:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add(
        "Default", 
        new MyRoute(
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        )
    );
}

当您发布到

现在 /家居并设置接受请求头 XML 首页控制器 XML 的行动将受到打击。

Now when you POST to /home and set the Accept request header to xml the Xml action of the Home controller will be hit.

这篇关于随着MVC3,我怎么可以改变的基础上的&QUOT控制器/动作;同意]头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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