将QueryString解析为强类型对象

时间:2016-06-08 13:13:12

标签: c# asp.net-mvc

我知道它可以自动完成;

class Query 
{ 
     public int?[] Id { get; set; }
}

public ActionResult Index(Query q)
{
}

一些QueryString /index?id=10&id=11

它完美无瑕。

但在某些情况下我只能请求:

Reqest.RawUrl

可以使用内置解析来创建查询对象吗?

Query q = SomeMagicStuff<Query>(Request.RawUrl);

2 个答案:

答案 0 :(得分:3)

是的,这是可能的。如果你使用MVC,你可以使用MVC DefaultModelBinder我为这种情况写一个函数:

public class MyModelBinder<T>
{
    private ModelBindingContext modelBindingContext = new ModelBindingContext();

    /// <summary>
    /// Method to get model from QueryString
    /// </summary>
    /// <param name="request">HttpRequest</param>
    /// <returns>T model</returns>
    public static T GetModelFromQueryString(HttpRequest request)
    {
        modelBindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
        modelBindingContext.ValueProvider = new NameValueCollectionValueProvider(request.QueryString, System.Globalization.CultureInfo.InvariantCulture);
        IModelBinder mb = new DefaultModelBinder();
        return (T)mb.BindModel(new ControllerContext(), modelBindingContext);
    }

    /// <summary>
    /// Method to get model from FormColletion
    /// </summary>
    /// <param name="request">HttpRequest</param>
    /// <returns>T model</returns>
    public static T GetModelFromFormColletion(HttpRequest request)
    {
        modelBindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
        modelBindingContext.ValueProvider = new NameValueCollectionValueProvider(request.Params, System.Globalization.CultureInfo.InvariantCulture);
        IModelBinder mb = new DefaultModelBinder();
        return (T)mb.BindModel(new ControllerContext(), modelBindingContext);
    }
}

请注意,有两种方法。它们仅与request.Paramsrequest.QueryString不同。

答案 1 :(得分:0)

序列化查询字符串并反序列化到您的类对象

> type Foo() = class end
> let m = Map [(Foo(), "bar")]
error FS0001: The type 'Foo' does not support the 'comparison' constraint