无法访问Basecontroller MVC4的BeginExecuteCore()方法中的Request.Headers

时间:2013-11-06 13:31:55

标签: asp.net-web-api

任何人都可以帮帮我吗?我正在尝试在我的mvc 4 WebApi应用程序中实现本地化。我希望在此基础上向用户显示特定于文化的页面 “用户区域设置”在请求标头中传递。

我所做的是,我有一个LinkedAccountModel类,如下所示 -

 public class LinkedAccountModel
{

    public string Id { get; set; }

    [Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "DomainNameRequired")]
    [DataType(DataType.Password)]
    [Display(Name = "DomainName", ResourceType = typeof(LanguageResources.Resource))]
    public string DomainName { get; set; }


    [Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "UserNameRequired")]
    [Display(Name = "UserName", ResourceType = typeof(LanguageResources.Resource))]
    public string UserName { get; set; }


    [Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "PasswordRequired")]
    [DataType(DataType.Password)]
    [Display(Name = "Password", ResourceType = typeof(LanguageResources.Resource))]
    public string Password { get; set; }

    [Required(ErrorMessageResourceType = typeof(LanguageResources.Resource), ErrorMessageResourceName = "ServerNameRequired")]
    [Display(Name = "ServerName", ResourceType = typeof(LanguageResources.Resource))]
    public string ServerName { get; set; }

    [Required]
    public long UserId { get; set; }
}

=============================================== =========================

有了这个,我有一个使用这个模型的ExchangeAccountSetupController。该控制器由BaseController实现。我的ExchangeAccountSetupController如下所示 -

public class ExchangeAccountSetupController : BaseController
{
    private PersistenceManagerAsync _persistenceManager;

    public async Task<ActionResult> New(string sessionToken)
    {
        if (string.IsNullOrEmpty(sessionToken))
        {               
            ViewBag.Title = LanguageResources.Resource.AccountConfigurationFailed;
            ViewBag.ErrorMessage = LanguageResources.Resource.UnableToProcessRequest;

            return View("Message");
        }

        _persistenceManager = new PersistenceManagerAsync(null);
        var token = await _persistenceManager.RetrieveAsync<SessionToken>(string.Format("{0}|{1}", sessionToken.Substring(0, 10), sessionToken));
        if (token == null)
        {                
            ViewBag.Title = LanguageResources.Resource.AccountConfigurationFailed;
            ViewBag.ErrorMessage = LanguageResources.Resource.UnableToProcessRequest;
            return View("Message");
        }

        _persistenceManager = new PersistenceManagerAsync(token);
        var user = new User { UserId = token.UserId };
        var linkedAccount = await LinkedAccountManager.RetrieveLinkedAccount(_persistenceManager, user, "Exchange");
        var linkedAccountModel = new LinkedAccountModel { UserId = token.UserId };

        var existingUser = await _persistenceManager.RetrieveAsync<User>(user.PartitionKey, user.RowKey);          
        if (linkedAccount != null)
        {
            ViewBag.Title = LanguageResources.Resource.ChangePassword;

            linkedAccountModel.DomainName = linkedAccount.DomainName;
            linkedAccountModel.UserName = linkedAccount.UserName;
            if (!string.IsNullOrEmpty(linkedAccount.Url))
                linkedAccountModel.ServerName = new Uri(linkedAccount.Url).Host;
            return View("New", linkedAccountModel);
        }
        ViewBag.Title = LanguageResources.Resource.ConfigureNewExchangeAccount; //default title.
        return View("New", linkedAccountModel);
    }

=============================================== =========================

我的BaseController如下所示 -

public class BaseController : Controller
{
    protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
    {
        string currentLocale = string.Empty;
        if (Request.Headers["User-Locale"] == null || string.IsNullOrEmpty(Request.Headers["User-Locale"]))
            currentLocale = "en-US";
        else
            currentLocale = Request.Headers["User-Locale"];
        // Modify current thread's cultures                        
        string[] localeKeys = currentLocale.Split('-');
        if (localeKeys[0].Equals("en"))
            currentLocale = "en-US";
        else if (localeKeys[0].Equals("nl"))
            currentLocale = "nl-NL";
        else
            currentLocale = "en-US";

        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(currentLocale);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

        return base.BeginExecuteCore(callback, state);
    }
}

=============================================== =========================

我的客户端应用程序仅在Dotnet中。我正在向“ExchangeAccountSetupController”控制器的New()Action发送请求。

这是我在HttpClient Request-

中添加标题的客户端应用程序代码
 var client = new HttpClient();

client.Timeout = new TimeSpan(1,1,1);   client.DefaultRequestHeaders.Add(“User-Locale”,“nl-NL”);

var webResponse = httpClient.GetAsync(RestServiceUrl.GetLinkedAccountProviderUrl(accountProviderName))。结果;             if(webResponse.StatusCode!= HttpStatusCode.OK)                 return null;

        var url = JsonConvert.DeserializeObject<string>(webResponse.Content.ReadAsStringAsync().Result);
        return url;    

我的问题是每当我从客户端发送请求时,请求都成功到达BaseController。但是我无法在BeginExecuteCore()方法下访问当前Request对象中的“User-Locale”。我无法从Request对象访问“User-Locale”标头。我在Request.Headers [“User-Locale”]中没有得到任何东西。它给我null。

请告诉我我是否做错了。即使我不确定我是否可以在BeginExecuteCore()方法下访问该标题。我们非常感谢任何建议。

1 个答案:

答案 0 :(得分:1)

HTTP中没有定义User-Locale标头。您可能正在寻找Accept-Language标题 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 从MVC Web API,你可以得到它 Request.Headers.AcceptLanguage

您还可以使用此属性获取已解析的语言列表 HttpContext.Current.Request.UserLanguages
请注意,列表没有排序,与文档说的相反 http://msdn.microsoft.com/en-us/library/system.web.httprequest.userlanguages(v=vs.110).aspx