Getting HttpRequest extension method written for M

2019-08-06 10:04发布

问题:

I'm working with OAuth 2.0 for MVC, a .NET library for Oauth2. I'm building a Web Api project, however, and am hoping to get this library to work with Web Api.

The problem I'm running into is that the library uses two extension methods on the HttpRequestBase that it calls from the controller.

Here are the extension methods:

public static string GetToken(this HttpRequest request)
    {
        var wrapper = new HttpRequestWrapper(request);
        return GetToken(wrapper);
    }

    public static string GetToken(this HttpRequestBase request)
    {
        if (request == null)
            return String.Empty;

        // Find Header
        var headerText = request.Headers[OAuthConstants.AuthorzationHeader];
        if (!String.IsNullOrEmpty(headerText))
        {
            var header = new AuthorizationHeader(headerText);
            if (string.Equals(header.Scheme, "OAuth", StringComparison.OrdinalIgnoreCase))
                return header.ParameterText.Trim();
        }

        // Find Clean Param
        var token = request.Params[OAuthConstants.AuthorzationParam];
        return !String.IsNullOrEmpty(token)
            ? token.Trim()
            : String.Empty;
    }

In the MVC project, they simply call Request.GetToken() from the controller. Of course, Web Api's request is an HttpRequestMessage. I'm afraid addressing the difference between HttpRequest and HttpRequest message is beyond my capabilities right now.

Can I convert this extension method to work with HttpRequestMessage or somehow make it work in Web Api??

Thanks!

回答1:

All the properties you used to have are still available (assuming the OAuthConstants.AuthorzationParam is set on the query string?)

using System;
using System.Linq;
using System.Net.Http;

namespace YourApp
{
    public static class Extensions
    {
        public static string GetToken(this HttpRequestMessage request)
        {
           if (request == null)
               return String.Empty;

           // Find Header
           var headerText = request.Headers.GetValues(OAuthConstants.AuthorzationHeader).SingleOrDefault();
           if (!String.IsNullOrEmpty(headerText))
           {
               //Brevity...
           }

           // Find Clean Param
           var token = request.GetQueryNameValuePairs().SingleOrDefault(x => x.Key == OAuthConstants.AuthorzationParam).Value;
           return !String.IsNullOrEmpty(token)
               ? token.Trim()
               : String.Empty;
       }
   }

}

Controller

using System.Collections.Generic;
using System.Web.Http;
using YourApp;

namespace YourApp.Controllers
{
    public class FoosController : ApiController
    {
        public IEnumerable<string> Get()
        {
            var token = Request.GetToken();

            return null;
        }
    }
}