Neo*_*Neo 3 c# asp.net-web-api
我创建了一个custom AuthorizeAttribute验证一些OAuth credentials of user.
一旦我获得有效的用户,我想将响应数据返回到控制器,如何在 web api .net 中实现此目的。
public class CustomAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var response = mydata.Result.Content.ReadAsStringAsync();
if (mydata.Result.StatusCode == HttpStatusCode.OK)
{
// return response data to controller
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我搜了一下我得到in mvc了can be done like below。
public class CustomAttribute : AuthorizeAttribute
{
public string BlackListedUsers { get; set; }
protected override bool AuthorizeCore(AuthorizationContext filterContext)
{
filterContext.HttpContext.Items["test"] = "foo";
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中 -
_yourVariable = HttpContext.Items["test"];
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这一目标,System.Web.Http因为web api在 webapi 中我没有method AuthorizeCore and input parameter AuthorizationContext?
这种方法可行,但不推荐。
在您的 IsAuthorized 函数内 -
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var response = mydata.Result.Content.ReadAsStringAsync();
if (mydata.Result.StatusCode == HttpStatusCode.OK)
{
string someValue = "any value";
actionContext.Request.Properties.Add(new KeyValuePair<string, object>("YourKeyName", someValue));
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
可以someValue是字符串、整数或任何您想要的自定义对象。
在控制器中你像这样检索-
object someObject;
Request.Properties.TryGetValue("YourKeyName", out someObject);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3083 次 |
| 最近记录: |