首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Request.Url.Scheme未按预期工作

Request.Url.Scheme未按预期工作
EN

Stack Overflow用户
提问于 2016-03-28 13:35:17
回答 1查看 4.1K关注 0票数 4

我正在使用asp.net MVC。我的代码是:

代码语言:javascript
复制
var url = Url.Action(
                   "ConfirmEmail", "Account",
                   new { userId = id, code = code },
                   protocol: Request.Url.Scheme);

在本地主机上,它正在返回右url,即,

https://localhost:44300/Account/ConfirmEmail?userId=bed34d05-2b7b-49b8-940e-0d89d4870d17&code=AQAA

但在直播网站上,它并没有像预期的那样起作用。它返回的url是:

http://newtemp.apphb.com:16169/Account/ConfirmEmail?userId=7ba65316-0901-4c27-9371-588a5e945baa&code=AQAA

:16169部分是加法的。它是从哪里来的,怎么把它移除?

我的详细代码是:

代码语言:javascript
复制
public async Task<bool> SendMailtoConfirmEmailAddress(string id,string name,string email)
        {
            var user = await db.AspNetUsers.FindAsync(id);
            if (user.EmailConfirmed)
            {
                return false;
            }
            try
            {
                var provider = new DpapiDataProtectionProvider("http://newtemp.apphb.com/");
                UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, string>(provider.Create("UserToken"))
                    as IUserTokenProvider<ApplicationUser, string>;

                var code = await UserManager.GenerateEmailConfirmationTokenAsync(id);
                var callbackUrl = Url.Action(
                   "ConfirmEmail", "Account",
                   new { userId = id, code = code },
                   protocol: Request.Url.Scheme);

                ElectronicsController.sendEmail(email, "Welcome to dealkar.pk - Confirm Email address", "Hello " + name + "!<br/>Confirm your email address by clicking <a href=\"" + callbackUrl + "\">here</a> OR " + callbackUrl);

            }
            catch (Exception e)
            {
                string s = e.ToString();
            }
            return true;
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-28 17:46:16

从哪来的?

从当前请求解析端口。。不幸的是,Microsoft没有考虑在运行非默认端口的服务器上生成URL的时间,它将只使用当前端口(无论协议是否与当前请求相同)。

怎么移除这个?

您可以创建一个扩展方法,告诉UrlHelper使用默认端口,而不管传入请求的端口是哪个端口。

此示例基于默认端口( HTTP为80,HTTPS为443 )创建假HTTP上下文,然后使用UrlHelper的新实例解析URL。

代码语言:javascript
复制
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

public static class UrlHelperExtensions
{
    public static string Action(this UrlHelper helper, string actionName, string controllerName, object routeValues, string protocol, bool defaultPort)
    {
        return Action(helper, actionName, controllerName, routeValues, protocol, null, defaultPort);
    }

    public static string Action(this UrlHelper helper, string actionName, string controllerName, object routeValues, string protocol, string hostName, bool defaultPort)
    {
        if (!defaultPort)
        {
            return helper.Action(actionName, controllerName, new RouteValueDictionary(routeValues), protocol, hostName);
        }

        string port = "80";
        if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
        {
            port = "443";
        }

        Uri requestUrl = helper.RequestContext.HttpContext.Request.Url;
        string defaultPortRequestUrl = Regex.Replace(requestUrl.ToString(), @"(?<=:)\d+?(?=/)", port);
        Uri url = new Uri(new Uri(defaultPortRequestUrl, UriKind.Absolute), requestUrl.PathAndQuery);

        var requestContext = GetRequestContext(url);
        var urlHelper = new UrlHelper(requestContext, helper.RouteCollection);

        var values = new RouteValueDictionary(routeValues);
        values.Add("controller", controllerName);
        values.Add("action", actionName);

        return urlHelper.RouteUrl(null, values, protocol, hostName);
    }

    private static RequestContext GetRequestContext(Uri uri)
    {
        // Create a TextWriter with null stream as a backing stream 
        // which doesn't consume resources
        using (var writer = new StreamWriter(Stream.Null))
        {
            var request = new HttpRequest(
                filename: string.Empty,
                url: uri.ToString(),
                queryString: string.IsNullOrEmpty(uri.Query) ? string.Empty : uri.Query.Substring(1));
            var response = new HttpResponse(writer);
            var httpContext = new HttpContext(request, response);
            var httpContextBase = new HttpContextWrapper(httpContext);
            return new RequestContext(httpContextBase, new RouteData());
        }
    }
}

用法

代码语言:javascript
复制
        var url = Url.Action("ConfirmEmail", "Account",
               new { userId = 123, code = 456 },
               protocol: Request.Url.Scheme,
               defaultPort: true);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36263495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档