本文整理汇总了C#中System.Web.Mvc.UrlHelper.Encode方法的典型用法代码示例。如果您正苦于以下问题:C# UrlHelper.Encode方法的具体用法?C# UrlHelper.Encode怎么用?C# UrlHelper.Encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Web.Mvc.UrlHelper
的用法示例。
在下文中一共展示了UrlHelper.Encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetAccessToken
public string GetAccessToken(WorkContext wc, string code, string returnUrl)
{
try
{
var part = wc.CurrentSite.As<FacebookSettingsPart>();
var clientId = part.ClientId;
var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);
var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
var redirectUrl =
new Uri(wc.HttpContext.Request.Url,
urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth" })).ToString();//, returnUrl = returnUrl
var url = string.Format(TokenRequestUrl, urlHelper.Encode(clientId), urlHelper.Encode(redirectUrl), urlHelper.Encode(clientSecret), urlHelper.Encode(code));
var wr = WebRequest.Create(url);
wr.Proxy = OAuthHelper.GetProxy();
wr.Method = "GET";
var wres = wr.GetResponse();
using (var stream = wres.GetResponseStream())
using (var sr = new StreamReader(stream))
{
var result = HttpUtility.ParseQueryString(sr.ReadToEnd());
return result["access_token"];
}
}
catch (Exception ex)
{
string error = OAuthHelper.ReadWebExceptionMessage(ex);
Logger.Error(ex, string.IsNullOrEmpty(error) ? ex.Message : error);
}
return null;
}
示例2: AnonymousToFlashVars
/// <summary>
/// Concerts anonymous object into FlashVars string (like querystring but HTML encoded)
/// </summary>
/// <param name="html"></param>
/// <param name="values"></param>
/// <returns></returns>
public static IHtmlString AnonymousToFlashVars(this HtmlHelper html, UrlHelper url, object values) {
var dict = new RouteValueDictionary(values);
// HTML and URL encode, glue and convert
return MvcHtmlString.Create(
dict.Select(kv =>
html.Encode(url.Encode(kv.Key)) + "=" + html.Encode(url.Encode(kv.Value.ToString())))
.Glue("&"));
}
示例3: GetLogOnUrl
public string GetLogOnUrl(WorkContext context)
{
var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
var part = context.CurrentSite.As<FacebookSettingsPart>();
var clientId = part.ClientId;
var returnUrl = context.HttpContext.Request.Url;
var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth" })).ToString();//, returnUrl = returnUrl
return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), urlHelper.Encode(returnUrl.ToString()));
}
示例4: GetLogOnUrl
public string GetLogOnUrl(WorkContext context)
{
var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
var part = context.CurrentSite.As<RenrenSettingsPart>();
var clientId = part.ClientId;
var additional = part.Additional;
//用于第三方应用防止CSRF攻击,成功授权后回调时会原样带回。请务必严格按照流程检查用户与state参数状态的绑定.
var returnUrl = context.HttpContext.Request.Url;
var state = urlHelper.Encode(returnUrl.ToString());
var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "RenrenOAuth", new { Area = "Cabbage.OAuth" })).ToString();
return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), state, (string.IsNullOrWhiteSpace(additional) ? "" : ("&" + additional)));
}
示例5: Index
/// <summary>
/// Initial Index
/// </summary>
/// <returns>Index view</returns>
public ActionResult Index()
{
if (User.IsInRole("Instructor") || User.IsInRole("Administrator"))
{
return this.View();
}
else
{
User user = this.db.Query<User>().Where(u => u.EmailAddress == User.Identity.Name).FirstOrDefault();
if (user == null)
{
UrlHelper helper = new UrlHelper();
return this.Redirect("/Home/Error?Message=" + helper.Encode("User " + User.Identity.Name + " does not exist"));
}
DateTime start = DateTime.Now.AddHours(1);
List<Classroom> runningClassrooms = this.db.Query<Classroom>().Include(c => c.Course).Where(c => c.Start < start).ToList();
runningClassrooms = runningClassrooms.Where(c => c.Start.AddDays(c.Course.Days).AddHours(c.Course.Hours + 1) > DateTime.Now).ToList();
List<int> runningClassroomIds = runningClassrooms.Select(c => c.ClassroomId).ToList();
List<Seat> seats = this.db.Query<Seat>().Where(s => s.UserId == user.UserId && runningClassroomIds.Contains(s.ClassroomId)).ToList();
if (seats.Count == 0)
{
UrlHelper helper = new UrlHelper();
return this.Redirect("/Home/Error?Message=" + helper.Encode("Running Classrooms: " + runningClassrooms.Count + "<br/>"
+ "Classroom IDs :" + runningClassroomIds.ToString() + "<br/>"
+ "User Id :" + user.UserId));
}
return this.RedirectToAction("Connect", new { id = seats[0].SeatId });
}
}
示例6: Login
public ActionResult Login(LoginModel model, string returnUrl)
{
// No checking of password for this sample. Just care about the username
// as that's what we're including in the token to send back to the authorization server
// Corresponds to shared secret the authorization server knows about for this resource
const string encryptionKey = "WebAPIsAreAwesome";
// Build token with info the authorization server needs to know
var tokenContent = model.UserName + ";" + DateTime.Now.ToString(CultureInfo.InvariantCulture) + ";" + model.RememberMe;
var encryptedToken = EncodingUtility.Encode(tokenContent, encryptionKey);
// Redirect back to the authorization server, including the authentication token
// Name of authentication token corresponds to that known by the authorization server
returnUrl += (returnUrl.Contains("?") ? "&" : "?");
returnUrl += "resource-authentication-token=" + encryptedToken;
var url = new Uri(returnUrl);
var redirectUrl = url.ToString();
// URL Encode the values of the querystring parameters
if (url.Query.Length > 1)
{
var helper = new UrlHelper(HttpContext.Request.RequestContext);
var qsParts = HttpUtility.ParseQueryString(url.Query);
redirectUrl = url.GetLeftPart(UriPartial.Path) + "?" + String.Join("&",qsParts.AllKeys.Select(x => x + "=" + helper.Encode(qsParts[x])));
}
return Redirect(redirectUrl);
}
示例7: GetGoogleLogOnUrl
public static string GetGoogleLogOnUrl(this HtmlHelper htmlHelper, WorkContext workContext)
{
var urlHelper = new UrlHelper(workContext.HttpContext.Request.RequestContext);
var part = workContext.CurrentSite.As<GoogleSettingsPart>();
var clientId = part.ClientId;
var returnUrl = workContext.HttpContext.Request.Url;
var redirectUrl = new Uri(
returnUrl,
urlHelper.Action("GoogleAuth", "Account", new {area = "Teeyoot.Account"})
).ToString();
return string.Format(
GoogleUrl,
clientId,
urlHelper.Encode(redirectUrl),
urlHelper.Encode(Scope),
urlHelper.Encode(returnUrl.ToString()));
}
示例8: GetLogOnUrl
public string GetLogOnUrl(WorkContext context)
{
var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
var part = context.CurrentSite.As<LinkedInSettingsPart>();
var clientId = part.ClientId;
var returnUrl = context.HttpContext.Request.Url;
var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "LinkedInOAuth", new { Area = "RM.QuickLogOn.OAuth", ReturnUrl = returnUrl })).ToString();//
var state = Guid.NewGuid().ToString().Trim('{', '}');
return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), state);
}
示例9: GetAccessToken
private DoubanAccessTokenJsonModel GetAccessToken(WorkContext wc, string code)
{
try
{
var part = wc.CurrentSite.As<DoubanSettingsPart>();
var clientId = part.ClientId;
var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);
var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
var redirectUrl =
new Uri(wc.HttpContext.Request.Url,
urlHelper.Action("Auth", "DoubanOAuth", new { Area = "Cabbage.OAuth" })).ToString();
var encodeUrl = urlHelper.Encode(redirectUrl);
var wr = WebRequest.Create(string.Format(TokenRequestUrl, clientId, clientSecret, code, encodeUrl));
wr.Proxy = OAuthHelper.GetProxy();
wr.ContentType = "application/x-www-form-urlencoded";
wr.Method = "POST";
using (var stream = wr.GetRequestStream())
using (var ws = new StreamWriter(stream, Encoding.UTF8))
{
//此段参数为保险起见,加入的,实际上只需要URL拼接即可
ws.Write("client_id={0}&", clientId);
ws.Write("client_secret={0}&", clientSecret);
ws.Write("grant_type=authorization_code&");
ws.Write("code={0}&", code);
ws.Write("redirect_uri={0}", encodeUrl);
}
var wres = wr.GetResponse();
using (var stream = wres.GetResponseStream())
{
return OAuthHelper.FromJson<DoubanAccessTokenJsonModel>(stream);
}
}
catch (WebException ex)
{
var webResponse = ex.Response as HttpWebResponse;
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream))
{
var error = sr.ReadToEnd();
Logger.Error(ex, error);
}
}
catch (Exception ex)
{
Logger.Error(ex, ex.Message);
}
return null;
}
示例10: GravatarUrl
/// <summary>
/// Get only the url to retrieve the gravatar image
/// </summary>
/// <param name="helper"></param>
/// <param name="email"></param>
/// <param name="size"></param>
/// <returns></returns>
public static string GravatarUrl(this HtmlHelper helper, string email, int size)
{
if (email == null)
email = string.Empty;
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
string defaultAvatar = helper.ViewContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost") ? "wavatar" : urlHelper.Encode(WebHelper.GetSiteRoot() + "/Resources/img/gravatar-default.png");
return string.Concat("http://gravatar.com/avatar/",
email.ToLowerInvariant().EncryptToMD5(),
".jpg?s=", size, "&d=", defaultAvatar);
}
示例11: GetAccessToken
private string GetAccessToken(WorkContext wc, string code, string returnUrl)
{
try
{
var part = wc.CurrentSite.As<LinkedInSettingsPart>();
var clientId = part.ClientId;
var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);
var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
var redirectUrl =
new Uri(wc.HttpContext.Request.Url,
urlHelper.Action("Auth", "LinkedInOAuth", new { Area = "RM.QuickLogOn.OAuth", ReturnUrl = returnUrl })).ToString(); //
var url = string.Format(TokenRequestUrl,
urlHelper.Encode(clientId),
urlHelper.Encode(redirectUrl),
urlHelper.Encode(clientSecret),
urlHelper.Encode(code));
var wr = WebRequest.Create(url);
wr.Method = "POST";
wr.Proxy = OAuthHelper.GetProxy();
//if (ServicePointManager.ServerCertificateValidationCallback == null) ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => true);
var wres = wr.GetResponse();
using (var stream = wres.GetResponseStream())
{
var result = OAuthHelper.FromJson<LinkedInAccessTokenJsonModel>(stream);
return result.access_token;
}
}
catch (Exception ex)
{
string error = OAuthHelper.ReadWebExceptionMessage(ex);
Logger.Error(ex, error ?? ex.Message);
}
return null;
}
示例12: ToString
public override string ToString()
{
var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
var result = new StringBuilder();
if (base.AllKeys.Any())
result.Append("?");
foreach (var key in base.AllKeys)
{
string[] values = base.GetValues(key);
if (values != null && values.Count() > 0)
result.Append(key + "=" + url.Encode(values[0]) + "&");
}
string resultString = result.ToString();
return resultString.EndsWith("&") ? resultString.Substring(0, resultString.Length - 1) : resultString;
}
示例13: GetAccessToken
private string GetAccessToken(WorkContext wc, string code)
{
try
{
var part = wc.CurrentSite.As<QQSettingsPart>();
clientId = part.ClientId;
clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);
var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
var redirectUrl =
new Uri(wc.HttpContext.Request.Url,
urlHelper.Action("Auth", "QQOAuth", new { Area = "Cabbage.OAuth" })).ToString();
var wr = WebRequest.Create(string.Format(TokenRequestUrl, clientId, clientSecret, code, urlHelper.Encode(redirectUrl)));
wr.Proxy = OAuthHelper.GetProxy();
wr.ContentType = "application/x-www-form-urlencoded";
wr.Method = "GET";
var wres = wr.GetResponse();
using (var stream = wres.GetResponseStream())
using (var sr = new StreamReader(stream))
{
var result = HttpUtility.ParseQueryString(sr.ReadToEnd());
return result["access_token"];
}
}
catch (WebException ex)
{
var webResponse = ex.Response as HttpWebResponse;
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream))
{
var error = sr.ReadToEnd();
Logger.Error(ex, error);
}
}
catch (Exception ex)
{
Logger.Error(ex, ex.Message);
}
return null;
}
示例14: ImageLink
public static MvcHtmlString ImageLink(this HtmlHelper helper, string actionName,
string imageUrl, string alternateText, object routeValues,
object linkHtmlAttributes, object imageHtmlAttributes)
{
// Create an instance of the url helper class
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
// Set up variables for the parameters to be passed to the various methods
// of the helper to construct the html.
// Use the Action method to generate the correct Url
var url = urlHelper.Action(actionName, routeValues);
// Add any attributes to the RouteValueDictionary
var linkAttributes = new RouteValueDictionary(linkHtmlAttributes);
// Use the Content method to generate the url fot eh image (not an action url)
var imgUrl = urlHelper.Content(imageUrl);
// Use the Encode method to ensure any text is property encoded, to stop scripting attacks
var imgAltText = urlHelper.Encode(alternateText);
var imgAttributes = new RouteValueDictionary(imageHtmlAttributes);
// Create the Anchor tag to hold the href.
var linkTagbuilder = new TagBuilder("a");
// Add the href attribute
linkTagbuilder.MergeAttribute("href", url);
// Add any attributes passed into method.
linkTagbuilder.MergeAttributes(linkAttributes);
// Create the img tag to contain the image
var imageTagBuilder = new TagBuilder("img");
// Add the alt and src attributes
imageTagBuilder.MergeAttribute("alt", imgAltText);
imageTagBuilder.MergeAttribute("src", imgUrl);
// Add any additional attributes passed into the method.
imageTagBuilder.MergeAttributes(imgAttributes);
// Add the img tag inside the Anchor tag.
linkTagbuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing);
// Wrap the html in an MvcHtmlString and return.
// If we use the TagRenderMode.SelfClosing for this operation, it wipes out
// the innerHtml.
return new MvcHtmlString(linkTagbuilder.ToString());
}
示例15: OnActionExecuting
/// <summary>
/// Checks that the user is authenticated, and setsup the user. If User Setup fails, redirects to Activation page.
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (AuthenticatedController) filterContext.Controller;
if (!(controller is HIGController) && controller.OrgUser != null
&& ((controller.OrgUser.LatestHig != null && controller.OrgUser.LatestHig.CaptureDate.Date < DateTime.Today)
|| controller.OrgUser.LatestHig == null
)
)
{
var originalurl = filterContext.HttpContext.Request.Url.AbsolutePath;
var helper = new UrlHelper(filterContext.RequestContext);
var redirect = (originalurl == "/" ? "" : helper.Encode(originalurl));
filterContext.Result = String.IsNullOrEmpty(redirect) ? new RedirectResult("/HIG/HowsItGoing") : new RedirectResult(String.Format("/HIG/HowsItGoing?wctx={0}", redirect));
}
}