本文整理匯總了C#中System.Web.Mvc.ControllerContext類的典型用法代碼示例。如果您正苦於以下問題:C# ControllerContext類的具體用法?C# ControllerContext怎麽用?C# ControllerContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ControllerContext類屬於System.Web.Mvc命名空間,在下文中一共展示了ControllerContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if (controllerContext == null) {
throw new ArgumentNullException("controllerContext");
}
return new FormCollection(controllerContext.HttpContext.Request.Form);
}
示例2: ExecuteResultAsync
public async override Task ExecuteResultAsync(ControllerContext context)
{
ViewEngineResult result;
var viewContext = InitializeView(context, out result);
await viewContext.View.RenderAsync(viewContext, viewContext.Writer).ConfigureAwait(false);
ReleaseView(context, result);
}
示例3: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
if (base.Content == null)
{
//使用IMessageHandler輸出
if (_messageHandlerDocument == null)
{
throw new Senparc.Weixin.Exceptions.WeixinException("執行WeixinResult時提供的MessageHandler不能為Null!", null);
}
if (_messageHandlerDocument.FinalResponseDocument == null)
{
//throw new Senparc.Weixin.MP.WeixinException("FinalResponseDocument不能為Null!", null);
}
else
{
context.HttpContext.Response.ClearContent();
context.HttpContext.Response.ContentType = "text/xml";
var xml = _messageHandlerDocument.FinalResponseDocument == null
? ""
: _messageHandlerDocument.FinalResponseDocument
.ToString().Replace("\r\n", "\n"); //騰
using (MemoryStream ms = new MemoryStream())//迅
{//真
var bytes = Encoding.UTF8.GetBytes(xml);//的
context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);//很
}//疼
}
}
}
示例4: GetClientValidationRules
/// <summary>
/// When implemented in a class, returns client validation rules for that class.
/// </summary>
/// <param name="metadata">The model metadata.</param>
/// <param name="context">The controller context.</param>
/// <returns>
/// The client validation rules for this validator.
/// </returns>
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessageString ?? "Field invalid. Field can only contain alphanumeric characters: 'a-z', 'A-Z', '0-9'.", ValidationType = clientValidationRule };
rule.ValidationParameters.Add("pattern", RootModuleConstants.AlphanumericExpression);
yield return rule;
}
示例5: FindActionMethod
public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName)
{
Contract.Assert(controllerContext != null);
if (controllerContext.RouteData != null)
{
MethodInfo target = controllerContext.RouteData.GetTargetActionMethod();
if (target != null)
{
// short circuit the selection process if a direct route was matched.
return target;
}
}
List<MethodInfo> finalMethods = FindActionMethods(controllerContext, actionName, AliasedMethods, NonAliasedMethods);
switch (finalMethods.Count)
{
case 0:
return null;
case 1:
return finalMethods[0];
default:
throw CreateAmbiguousMatchException(finalMethods, actionName);
}
}
示例6: BindModel
/// <summary>
/// Binds the model to a value by using the specified controller context and binding context.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="bindingContext">The binding context.</param>
/// <returns>
/// The bound value.
/// </returns>
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
FacebookClient client = _config.ClientProvider.CreateClient();
dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
controllerContext.HttpContext,
rawSignedRequest =>
{
return client.ParseSignedRequest(rawSignedRequest);
});
if (signedRequest != null)
{
string accessToken = signedRequest.oauth_token;
string userId = signedRequest.user_id;
client.AccessToken = accessToken;
return new FacebookContext
{
Client = client,
SignedRequest = signedRequest,
AccessToken = accessToken,
UserId = userId,
Configuration = _config
};
}
else
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);
}
return null;
}
示例7: BindModel
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
//get the car from the session
Cart cart = null;
if (controllerContext.HttpContext.Session != null)
{
cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
}
//create the Cart if there wasn't one in the session data
if(cart == null)
{
cart = new Cart();
if (controllerContext.HttpContext.Session != null)
{
controllerContext.HttpContext.Session[sessionKey] = cart;
}
}
return cart;
}
示例8: GetValidators
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) {
_adaptersLock.EnterReadLock();
try {
List<ModelValidator> results = new List<ModelValidator>();
if (AddImplicitRequiredAttributeForValueTypes &&
metadata.IsRequired &&
!attributes.Any(a => a is RequiredAttribute)) {
attributes = attributes.Concat(new[] { new RequiredAttribute() });
}
foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {
DataAnnotationsModelValidationFactory factory;
if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {
factory = DefaultAttributeFactory;
}
results.Add(factory(metadata, context, attribute));
}
return results;
}
finally {
_adaptersLock.ExitReadLock();
}
}
示例9: CanFormat
public bool CanFormat(ControllerContext context, object resource, string mimeType)
{
return ((_targetMimeType == mimeType)
|| string.IsNullOrEmpty(_targetMimeType)
|| (alsoAcceptRequestsToFormat!=null&&alsoAcceptRequestsToFormat.Contains(mimeType)))
&& FindView(context, resource).View != null;
}
示例10: ExecuteResult
public override void ExecuteResult(ControllerContext controllerContext)
{
if (controllerContext != null)
{
var request = controllerContext.HttpContext.Request;
object callback = request[CALLBACK_QUERYSTRING];
if (callback == null)
{
controllerContext.RouteData.Values.TryGetValue(CALLBACK_QUERYSTRING, out callback);
}
var hasCallback = !string.IsNullOrWhiteSpace(callback == null ? "" : callback as string);
if (hasCallback)
{
SetContentTypeIfEmpty();
var response = controllerContext.HttpContext.Response;
response.Write(callback);
response.Write("(");
base.ExecuteResult(controllerContext);
response.Write(")");
}
else
{
base.ExecuteResult(controllerContext);
}
}
}
示例11: ExecuteResult
/// <summary>
/// El código es el mismo de ASP.NET MVC 3, cambie el método que escribe en el response
/// http://aspnet.codeplex.com/SourceControl/changeset/view/63930#266491
/// </summary>
/// <param name = "context"></param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
var response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
} else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.Converters.Add(new IsoDateTimeConverter());
response.Write(JsonConvert.SerializeObject(this.Data, Formatting.None, settings));
}
}
示例12: BindModel
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null) {
throw new ArgumentNullException("bindingContext");
}
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
// case 1: there was no <input ... /> element containing this data
if (valueResult == null) {
return null;
}
string value = valueResult.AttemptedValue;
// case 2: there was an <input ... /> element but it was left blank
if (String.IsNullOrEmpty(value)) {
return null;
}
// Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
// then we need to remove these quotes put in place by the ToString() method.
string realValue = value.Replace("\"", String.Empty);
return Convert.FromBase64String(realValue);
}
示例13: FindView
ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache, bool partial)
{
if (controllerContext == null) throw new ArgumentNullException("controllerContext");
RouteData routeData = controllerContext.RouteData;
string baseLocation = routeData.DataTokens[DataTokenKeys.ViewsLocation] as string;
ViewEngineResult result;
if (!String.IsNullOrEmpty(baseLocation)) {
string controller = routeData.GetRequiredString("controller");
string location = String.Concat(baseLocation, "/", controller);
routeData.Values["controller"] = location;
result = (partial) ?
this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache)
: this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache);
routeData.Values["controller"] = controller;
} else {
result = (partial) ?
this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache)
: this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache);
}
return result;
}
示例14: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;
int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();
IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);
string[] splitIds = selectedProfilePictureIds.Split(',');
List<int> selectedProfilePictures = new List<int>();
foreach (string id in splitIds) {
if (id != string.Empty) {
selectedProfilePictures.Add(Int32.Parse(id));
}
}
return new PhotosModel() {
UserId = myUserId,
ProfilePictureURL = myProfilePictureURL,
Photos = myPhotos,
SelectedPhotos = selectedProfilePictures
};
}
示例15: BindModel
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return Serializer.Deserialize(stringified, bindingContext.ModelType);
}