Joã*_*nes 10 c# oauth visual-studio odata asp.net-web-api
我开发了一个实现OAuth2.0和OData的WebApi.
现在我正在建立一个客户端来测试到目前为止我已经实现了什么.我使用OData客户端代码生成器为OData生成了模板,但是如何在OData请求中引入de访问令牌?
知道如何扩展OData模板以引入OAuth2.0方案吗?或者更简单的方法是,如何在每个OData请求中引入OAuth访问令牌?
static void Main(string[] args)
{
var container = new Default.Container(new Uri(baseurl));
TokenResponse accessToken = null;
try
{
accessToken = GetToken();
}
catch (Exception ex)
{
Console.WriteLine("Can't do nothing without an access token...");
return;
}
//I want to introduce in every request the following information:
//Basic autentication header with cliendId + clientSecret
//Access token
//How do I introduce them before making the call on the OData service?
foreach (var s in container.ServiceSessions)
{
string format = ";
Console.WriteLine("PKID:{0}", s.PKID);
}
}
Run Code Online (Sandbox Code Playgroud)
Joã*_*nes 16
经过一番研究后我找到了解决方案:
var container = new Default.Container(new Uri(http://localhost:9000/));
//Registering the handle to the BuildingRequest event.
container.BuildingRequest += (sender, e) => OnBuildingRequest(sender, e, accessToken);
//Every time a OData request is build it adds an Authorization Header with the acesstoken
private static void OnBuildingRequest(object sender, BuildingRequestEventArgs e, TokenResponse token)
{
e.Headers.Add("Authorization", "Bearer " + token.AccessToken);
}
Run Code Online (Sandbox Code Playgroud)
如果您想将访问令牌添加为HTTP请求标头,以下示例应该有所帮助:
var context = new DefaultContainer(new Uri("http://host/service/"));
context.SendingRequest2 += (s, e) => e.RequestMessage.SetHeader("headerName", "headerValue");
Run Code Online (Sandbox Code Playgroud)
在您指定此代码后发送的每个请求都将包含此标头.
| 归档时间: |
|
| 查看次数: |
2950 次 |
| 最近记录: |