[英]Parse QueryString into strongly typed object
我知道它可以自动完成;
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.Params
和request.QueryString
。
序列化查询字符串并反序列化为您的类对象
JObject json;
Request.RequestUri.TryReadQueryAsJson(out json);
string sjson = JsonConvert.SerializeObject(json);
Query query = JsonConvert.DeserializeObject<Query>(sjson);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.