Использование сведений о профиле с ASP.NET AJAX
Обновлен: Ноябрь 2007
Профиль ASP.NET веб-службы позволяет использовать службу приложения профиля ASP.NET в приложениях . В этом разделе показано, как вызвать службу профиля приложения ASP.NET из обозревателя с помощью кода ECMAScript (JavaScript).
Использование сведений о профиле требует, чтобы сначала была включена служба профилей в веб-узле. Таким образом, эта служба становится доступной в качестве веб-службы. Когда профиль веб-службы включен, можно вызывать этот профиль с помощью методов класса клиентского сценария Sys.Services.ProfileService.
Включение службы профилей
Чтобы использовать службы профиля из клиентского сценария, необходимо включить эти службы с помощью следующего элемента в файле приложения Web.config:
<system.web.extensions>
<scripting>
<webServices
< profileService enabled="true" />
</webServices
</scripting>
</system.web.extensions>
По умолчанию свойства профиля отсутствуют. Чтобы сделать свойство профиля доступным в клиентском приложения, добавьте имя свойства в атрибут readAccessProperties элемента profileService. Таким же образом для каждого свойства серверного профиля, которое может быть установлено в зависимости от данных, отправленных клиентским приложением, добавьте имя свойства в атрибут writeAccessProperties. В следующем примере показано, как предоставлять доступ к отдельным свойствам и задавать для клиентского приложения права на чтение и запись этих свойств:
<profileService enabled="true"
readAccessProperties="Backgroundcolor,Foregroundcolor"
writeAccessProperties=" Backgroundcolor,Foregroundcolor"/>
Свойства профиля определяются в разделе profile с помощью синтаксиса, подобного синтаксису в следующем примере. Для сгруппированных свойств используйте элемент group.
<system.web>
<profile enabled="true">
<add name=" Backgroundcolor" type="System.String"
defaultValue="white" />
<add name=" Foregroundcolor" type="System.String"
defaultValue="black" />
<properties>
<group name="Address">
<add name="Street" type="System.String" />
<add name="City" type="System.String"/>
<add name="PostalCode" type="System.String" />
</group>
</properties>
</profile>
</system.web>
Дополнительные сведения см. в разделе Практическое руководство. Конфигурация служб ASP.NET в ASP.NET AJAX.
Пример
В следующем примере показано, как использовать службу профиля из клиентского сценария. В данный пример входит веб-страница ASP.NET, которая содержит элемент управления ScriptManager. Когда этот элемент управления включен в страницу, объект Sys.Services.AuthenticationService автоматически становится доступным для любого клиентского сценария на странице.
Страница содержит кнопку входа со связанным обработчиком событий с именем OnClickLogin. В коде данного метода вызывается метод login объекта AuthenticationService.
После входа в систему вызывается функция обратного вызова loginComplete, в которой вызывается метод load объекта Sys.Services.ProfileService, чтобы загрузить профиль для текущего пользователя.
Сведения о профилях состоят из фонового и основного цветов, которые можно устанавливать после входа в систему. Фоновый и основной цвета являются свойствами профиля, которые необходимо задавать в файле Web.config. Чтобы определить эти свойства, добавьте следующие элементы в файл приложения Web.config:
<profile enabled="true">
<properties>
<add name="Backgroundcolor" type="System.String"
defaultValue="white"/>
<add name="Foregroundcolor" type="System.String"
defaultValue="black"/>
</properties>
</profile>
В коде данного примера предоставлены функции асинхронного завершаемого обратного вызова для загрузки и сохранения методов. Также можно добавить функции обратного вызова, завершившиеся неудачно, для загрузки и сохранения методов.
Примечание. |
---|
Перед выполнением этого примера убедитесь, что имеется по крайней мере один пользователь, определенный в базе данных членства приложения. Сведения о создании пользователя в стандартной базе данных SQL Server, экспресс-выпуск, содержатся в разделе Использование проверки подлинности с помощью форм в ASP.NET AJAX. |
var setProfileProps;
function pageLoad()
{
var userLoggedIn =
Sys.Services.AuthenticationService.get_isLoggedIn();
// alert(userLoggedIn);
profProperties = $get("setProfileProps");
passwordEntry = $get("PwdId");
if (userLoggedIn == true)
{
LoadProfile();
GetElementById("setProfProps").style.visibility = "visible";
GetElementById("logoutId").style.visibility = "visible";
}
else
{
DisplayInformation("User is not authenticated.");
}
}
// The OnClickLogout function is called when
// the user clicks the Logout button.
// It logs out the current authenticated user.
function OnClickLogout()
{
Sys.Services.AuthenticationService.logout(
null, OnLogoutComplete, AuthenticationFailedCallback,null);
}
function OnLogoutComplete(result,
userContext, methodName)
{
// Code that performs logout
// housekeeping goes here.
}
// This is the callback function called
// if the authentication failed.
function AuthenticationFailedCallback(error_object,
userContext, methodName)
{
DisplayInformation("Authentication failed with this error: " +
error_object.get_message());
}
// Loads the profile of the current
// authenticated user.
function LoadProfile()
{
Sys.Services.ProfileService.load(null,
LoadCompletedCallback, ProfileFailedCallback, null);
}
// Saves the new profile
// information entered by the user.
function SaveProfile()
{
// Set background color.
Sys.Services.ProfileService.properties.Backgroundcolor =
GetElementById("bgcolor").value;
// Set foreground color.
Sys.Services.ProfileService.properties.Foregroundcolor =
GetElementById("fgcolor").value;
// Save profile information.
Sys.Services.ProfileService.save(null,
SaveCompletedCallback, ProfileFailedCallback, null);
}
// Reads the profile information and displays it.
function LoadCompletedCallback(numProperties, userContext, methodName)
{
document.bgColor =
Sys.Services.ProfileService.properties.Backgroundcolor;
document.fgColor =
Sys.Services.ProfileService.properties.Foregroundcolor;
}
// This is the callback function called
// if the profile was saved successfully.
function SaveCompletedCallback(numProperties, userContext, methodName)
{
LoadProfile();
// Hide the area that contains
// the controls to set the profile properties.
SetProfileControlsVisibility("hidden");
}
// This is the callback function called
// if the profile load or save operations failed.
function ProfileFailedCallback(error_object, userContext, methodName)
{
alert("Profile service failed with message: " +
error_object.get_message());
}
// Utility functions.
// This function sets the visibilty for the
// area containing the page elements for settings
// profiles.
function SetProfileControlsVisibility(currentVisibility)
{
profProperties.style.visibility = currentVisibility;
}
// Utility function to display user's information.
function DisplayInformation(text)
{
document.getElementById('placeHolder').innerHTML +=
"<br/>"+ text;
}
function GetElementById(elementId)
{
var element = document.getElementById(elementId);
return element;
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
<%@ Page Language="VB" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Using Profile Service</title>
<style type="text/css">
body { font: 11pt Trebuchet MS;
padding-top: 72px;
text-align: center }
.text { font: 8pt Trebuchet MS }
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManagerId">
<Scripts>
<asp:ScriptReference Path="Profile.js" />
</Scripts>
</asp:ScriptManager>
<h2>Profile Service</h2>
<p>
You must log in first to set or get profile data.
Create a new user, if needed. <br /> Refer to the Authentication example.
</p>
<div id="loginId" style="visibility:visible">
<table id="loginForm">
<tr>
<td>User Name: </td>
<td><input type="text"
id="userId" name="userId" value=""/></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password"
id="userPwd" name="userPwd" value="" /></td>
</tr>
<tr>
<td><input type="button"
id="login" name="login" value="Login"
onclick="OnClickLogin()" /></td>
</tr>
</table>
</div>
<div id="setProfProps" style="visibility:hidden">
<input type="button"
value="Set Profile Properties"
onclick="SetProfileControlsVisibility('visible')"/>
</div>
<div id="placeHolder" style="visibility:visible" />
<br />
<input id="logoutId" type="button"
value="Logout" style="visibility:hidden"
onclick="OnClickLogout()" />
<div id="setProfileProps" style="visibility:hidden">
<table>
<tr>
<td>Foreground Color</td>
<td><input type="text" id="fgcolor"
name="fgcolor" value=""/></td>
</tr>
<tr>
<td>Background Color</td>
<td><input type="text" id="bgcolor"
name="bgcolor" value="" /></td>
</tr>
<tr>
<td><input type="button"
id="saveProf" name="saveProf"
value="Save Profile Properties"
onclick="SaveProfile();" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Using Profile Service</title>
<style type="text/css">
body { font: 11pt Trebuchet MS;
padding-top: 72px;
text-align: center }
.text { font: 8pt Trebuchet MS }
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManagerId">
<Scripts>
<asp:ScriptReference Path="Profile.js" />
</Scripts>
</asp:ScriptManager>
<h2>Profile Service</h2>
<p>
You must log in first to set or get profile data.
Create a new user, if needed. <br />
</p>
<div id="setProfProps" style="visibility:visible">
<input type="button"
value="Set Profile Properties"
onclick="SetProfileControlsVisibility('visible')"/>
</div>
<div id="placeHolder" style="visibility:visible" />
<br />
<input id="logoutId" type="button"
value="Logout" style="visibility:hidden"
onclick="OnClickLogout()" />
<div id="setProfileProps" style="visibility:hidden">
<table>
<tr>
<td>Foreground Color</td>
<td><input type="text" id="fgcolor"
name="fgcolor" value=""/></td>
</tr>
<tr>
<td>Background Color</td>
<td><input type="text" id="bgcolor"
name="bgcolor" value="" /></td>
</tr>
<tr>
<td><input type="button"
id="saveProf" name="saveProf"
value="Save Profile Properties"
onclick="SaveProfile();" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
См. также
Задачи
Практическое руководство. Конфигурация служб ASP.NET в ASP.NET AJAX
Основные понятия
Использование веб-служб в технологии AJAX ASP.NET
Вызов веб-служб из клиентского сценария
Использование проверки подлинности с помощью форм в ASP.NET AJAX