我知道它可以自动完成;

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

最佳答案

对的,这是可能的。如果您使用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);
    }
}


请注意,有2种方法。它们仅在request.Paramsrequest.QueryString上有所不同。

关于c# - 将QueryString解析为强类型对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37703540/

10-12 01:27