读取ASP.NET WEB API中的每个传入请求(URL) [英] Reading every incoming request (URL) in ASP.NET WEB API

查看:655
本文介绍了读取ASP.NET WEB API中的每个传入请求(URL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET MVC框架.在此框架中,我们检查了每个传入请求(url)的某个键并将其分配给属性.我们创建了一个自定义类,该类源自Controller class&我们覆盖 OnActionExecuting()以提供我们的自定义逻辑.

I was using ASP.NET MVC framework. In this framework, we checked every incoming request (url) for some key and assigned it to a property. We created a custom class which derived from Controller class & we override OnActionExecuting() to provide our custom logic.

我们如何在ASP.NET WEB API中实现相同的目标?

//Implementation from ASP.NET MVC

public class ApplicationController : Controller
{       
    public string UserID { get; set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!string.IsNullOrEmpty(Request.Params["uid"]))
            UserID = Request.Params["uid"];

        base.OnActionExecuting(filterContext);
    }    
}

我在ASP.NET WEB API中尝试过的方法:-尽管此方法有效,但我想知道这是否是正确的方法吗?

What I have tried in ASP.NET WEB API: -- Though this is working, I wonder if this is the correct approach?

创建了基本控制器

public class BaseApiController : ApiController
    {
        public string UserID { get; set; }
    }

创建了另一个继承ActionFilterAttribute类&的类.我重写了OnActionExecuting()

public class TokenFilterAttribute : ActionFilterAttribute
    {
       public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
            {
                var queryString = actionContext.Request.RequestUri.Query;
                var items = HttpUtility.ParseQueryString(queryString);
                var userId = items["uid"];

                ((MyApi.Data.Controllers.BaseApiController)(actionContext.ControllerContext.Controller)).UserID = userId;


            }
  }

现在注册该课程

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new TokenFilterAttribute());
} 

推荐答案

您可以使用ASP.NET Web API中的消息处理程序.当您需要从查询字符串,URL或HTTP标头中获取一些用户令牌时,这是一种典型的安全场景.

You can use message handlers from ASP.NET Web API. It is a typical security scenation, when you need to get some user token from query string, URL or HTTP Header

http://www.asp.net/web- api/overview/advanced/http-message-handlers

1.当您只需要从URL中提取userId时,然后将其用作您的Api方法的参数,ASP.NET WebAPI就可以为您工作,例如

1.When you need simply to extract userId from URL, then use it as parameter for your Api method and ASP.NET WebAPI will do work for you, like

[HttpGet, Route("{userId}/roles")]      
public UserRoles GetUserRoles(string userId, [FromUri] bool isExternalUser = true)

适用于此类请求

http://.../15222/roles?isExternalUser=false

2.如果是安全方案,请参考

2.If it is security scenario, please refer to http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api Basically you will need some MessageHandler or you can use filter attributes as well, it is mechanism in ASP.NET Web API to intercept each call.

如果您需要处理每个请求,那么可以使用MessageHandler.您需要实现MessageHanler,然后进行注册.

If you need to process each request then MessageHandler is your way. You need implement MessageHanler and then register it.

简单地说,典型的MessageHandler是从MessageHandler或DelegatingHandler派生的类,其中重写了SendAsync方法:

To say easily, typical MessageHandler is class derived from MessageHandler or DelegatingHandler with SendAsync method overriden:

class AuthenticationHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Your code here
        return base.SendAsync(request, cancellationToken);
     }
}

And you need register it 

static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {                   
        // Other code for WebAPI registerations here
        config.MessageHandlers.Add(new AuthenticationHandler());            
    }
}

并从Global.asax.cs调用它

and call it from Global.asax.cs

WebApiConfig.Register(GlobalConfiguration.Configuration);

WebApiConfig.Register(GlobalConfiguration.Configuration);

此类处理程序的一些虚拟假设实现(在这里,您需要从IPrincipal实现UidPrincipal,从IIdentity实现UidIdentity)

Some example dummy hypotetical implementation of such handler (here you need to imeplement your UidPrincipal from IPrincipal and UidIdentity from IIdentity)

public class AuthenticationHandler : DelegatingHandler
{       
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        try
        {
            var queryString = actionContext.Request.RequestUri.Query;
            var items = HttpUtility.ParseQueryString(queryString);
            var userId = items["uid"];

            // Here check your UID and maybe some token, just dummy logic
            if (userId == "D8CD2165-52C0-41E1-937F-054F24266B65")
            {           
                IPrincipal principal = new UidPrincipal(new UidIdentity(uid), null);

                // HttpContext exist only when hosting as asp.net web application in IIS or IISExpress
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = principal;
                }
                else
                {
                    Thread.CurrentPrincipal = principal;
                }
                return base.SendAsync(request, cancellationToken);
            }
            catch (Exception ex)
            {
                this.Log().Warn(ex.ToString());
                return this.SendUnauthorizedResponse(ex.Message);
            }
        }
        else
        {
            return this.SendUnauthorizedResponse();
        }
        }
        catch (SecurityTokenValidationException)
        {
            return this.SendUnauthorizedResponse();
        }
    }
}

并允许通过某些ASP.NET WebApi方法或WebAPI类中的某些属性对其进行访问

And lets access it from some ASP.NET WebApi method or some property in WebAPI class

var uid = ((UidIdentity)User.Identity).Uid

这篇关于读取ASP.NET WEB API中的每个传入请求(URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆