在MVC 4路由更改URL参数 [英] Changing URL parameters with routing in MVC 4

查看:156
本文介绍了在MVC 4路由更改URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的几个API函数允许参数叫做'属性'和'attributeDelimiter(奇异),这意味着预期的URL将是格式

SomeController / SomeAction AAA = BBB&放大器;属性= CCC&放大器; attributeDelimiter = DDD

我想允许在这些参数名称复数的支持,以及 - 属性和attributesDelimiter


  1. 有没有办法重新写在RouteConfig的网址是什么? (转动复数名奇异)

  2. 如果这是不可能的,或者它不会是最好的做法,这将是做这种最好的方式重新写?


解决方案

MVC不使用路由的查询字符串值。查询字符串值由<一个提供给动作方法href=\"http://www.c-sharpcorner.com/UploadFile/97fc7a/smart-working-with-custom-value-providers-in-Asp-Net-mvc/\"相对=nofollow>值提供。因此,要解决这个问题,你只需要一个自定义值提供程序来处理单数或复数的情况下。

示例

 使用系统;
使用System.Collections.Specialized;
使用System.Globalization;
使用System.Web.Mvc;公共类SingularOrPluralQueryStringValueProviderFactory:ValueProviderFactory
{
    私人只读字符串singularKey;
    私人只读字符串pluralKey;    公共SingularOrPluralQueryStringValueProviderFactory(字符串singularKey,串pluralKey)
    {
        如果(string.IsNullOrEmpty(singularKey))
            抛出新的ArgumentNullException(singularKey);
        如果(string.IsNullOrEmpty(pluralKey))
            抛出新的ArgumentNullException(pluralKey);        this.singularKey = singularKey;
        this.pluralKey = pluralKey;
    }    公众覆盖IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        返回新SingularOrPluralQueryStringValueProvider(this.singularKey,this.pluralKey,controllerContext.HttpContext.Request.QueryString);
    }
}公共类SingularOrPluralQueryStringValueProvider:IValueProvider
{
    私人只读字符串singularKey;
    私人只读字符串pluralKey;
    私人只读NameValueCollection中的queryString;
    公共SingularOrPluralQueryStringValueProvider(字符串singularKey,串pluralKey,NameValueCollection中的queryString)
    {
        如果(string.IsNullOrEmpty(singularKey))
            抛出新的ArgumentNullException(singularKey);
        如果(string.IsNullOrEmpty(pluralKey))
            抛出新的ArgumentNullException(pluralKey);        this.singularKey = singularKey;
        this.pluralKey = pluralKey;
        this.queryString =的queryString;
    }    公共BOOL包含preFIX(字符串preFIX)
    {
        返回this.GetSingularOrPluralValue(preFIX)!= NULL;
    }    公共ValueProviderResult的GetValue(字符串键)
    {
        VAR值= this.GetSingularOrPluralValue(键);
        返回(值!= NULL)?
            新ValueProviderResult(值,value.ToString(),CultureInfo.InvariantCulture):
            空值;
    }    私人布尔IsKeyMatch(字符串键)
    {
        回报(this.singularKey.Equals(键,StringComparison.OrdinalIgnoreCase)||
            this.pluralKey.Equals(键,StringComparison.OrdinalIgnoreCase));
    }    私人字符串GetSingularOrPluralValue(字符串键)
    {
        如果(this.IsKeyMatch(键))
        {
            返回this.queryString [this.singularKey]? this.queryString [this.pluralKey]
        }
        返回null;
    }
}

用法

 公共类MvcApplication:System.Web.HttpApplication
{
    保护无效的Application_Start()
    {
        AreaRegistration.RegisterAllAreas();        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();        //在列表的开头插入我们的价值供应商的工厂
        //所以他们覆盖默认QueryStringValueProviderFactory
        ValueProviderFactories.Factories.Insert(
            0,新SingularOrPluralQueryStringValueProviderFactory(属性,属性));
        ValueProviderFactories.Factories.Insert(
            1,新的SingularOrPluralQueryStringValueProviderFactory(attributeDelimiter,attributesDelimiter));
    }
}

现在在你的操作方法,甚至在你的模型的属性,价值是否被指定为查询字符串单数还是复数,值将被填充。如果两个单数和复数包括在查询串中,奇异值花费precedence

 公众的ActionResult指数(字符串属性,串attributeDelimiter)
{
    返回查看();
}

Several of my API functions allow parameters called 'attribute' and 'attributeDelimiter' (in singular), meaning the expected URL would be in the format of

SomeController/SomeAction?aaa=bbb&attribute=ccc&attributeDelimiter=ddd.

I would like to allow support for plural in those param names as well - 'attributes' and 'attributesDelimiter'.

  1. Is there a way to re-write the url in the RouteConfig? (turning the plural names to singular)
  2. If that is not possible or it wouldn't be the best practice, what would be the best way to do this kind of re-write?

解决方案

MVC does not use routing for query string values. Query string values are provided to action methods by value providers. So, to solve this issue you just need a custom value provider to handle the case of singular or plural.

Example

using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Web.Mvc;

public class SingularOrPluralQueryStringValueProviderFactory : ValueProviderFactory
{
    private readonly string singularKey;
    private readonly string pluralKey;

    public SingularOrPluralQueryStringValueProviderFactory(string singularKey, string pluralKey)
    {
        if (string.IsNullOrEmpty(singularKey))
            throw new ArgumentNullException("singularKey");
        if (string.IsNullOrEmpty(pluralKey))
            throw new ArgumentNullException("pluralKey");

        this.singularKey = singularKey;
        this.pluralKey = pluralKey;
    }

    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        return new SingularOrPluralQueryStringValueProvider(this.singularKey, this.pluralKey, controllerContext.HttpContext.Request.QueryString);
    }
}

public class SingularOrPluralQueryStringValueProvider : IValueProvider
{
    private readonly string singularKey;
    private readonly string pluralKey;
    private readonly NameValueCollection queryString;


    public SingularOrPluralQueryStringValueProvider(string singularKey, string pluralKey, NameValueCollection queryString)
    {
        if (string.IsNullOrEmpty(singularKey))
            throw new ArgumentNullException("singularKey");
        if (string.IsNullOrEmpty(pluralKey))
            throw new ArgumentNullException("pluralKey");

        this.singularKey = singularKey;
        this.pluralKey = pluralKey;
        this.queryString = queryString;
    }

    public bool ContainsPrefix(string prefix)
    {
        return this.GetSingularOrPluralValue(prefix) != null;
    }

    public ValueProviderResult GetValue(string key)
    {
        var value = this.GetSingularOrPluralValue(key);
        return (value != null) ? 
            new ValueProviderResult(value, value.ToString(), CultureInfo.InvariantCulture) : 
            null;
    }

    private bool IsKeyMatch(string key)
    {
        return (this.singularKey.Equals(key, StringComparison.OrdinalIgnoreCase) ||
            this.pluralKey.Equals(key, StringComparison.OrdinalIgnoreCase));
    }

    private string GetSingularOrPluralValue(string key)
    {
        if (this.IsKeyMatch(key))
        {
            return this.queryString[this.singularKey] ?? this.queryString[this.pluralKey];
        }
        return null;
    }
}

Usage

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        // Insert our value provider factories at the beginning of the list 
        // so they override the default QueryStringValueProviderFactory
        ValueProviderFactories.Factories.Insert(
            0, new SingularOrPluralQueryStringValueProviderFactory("attribute", "attributes"));
        ValueProviderFactories.Factories.Insert(
            1, new SingularOrPluralQueryStringValueProviderFactory("attributeDelimiter", "attributesDelimiter"));
    }
}

Now in your action methods or even on properties of your models, whether the value is specified as singular or plural in the query string, the values will be populated. If both singular and plural are included in the query string, the singular value takes precedence.

public ActionResult Index(string attribute, string attributeDelimiter)
{
    return View();
}

这篇关于在MVC 4路由更改URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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